46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
51 #include <unordered_map>
53 using namespace clang;
69 TypeNameValidatorCCC(
bool AllowInvalid,
bool WantClass =
false,
70 bool AllowTemplates =
false,
71 bool AllowNonTemplates =
true)
72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74 WantExpressionKeywords =
false;
75 WantCXXNamedCasts =
false;
76 WantRemainingKeywords =
false;
81 if (!AllowInvalidDecl && ND->isInvalidDecl())
85 return AllowTemplates;
87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
91 if (AllowNonTemplates)
97 auto *RD = dyn_cast<CXXRecordDecl>(ND);
98 if (!RD || !RD->isInjectedClassName())
100 RD = cast<CXXRecordDecl>(RD->getDeclContext());
101 return RD->getDescribedClassTemplate() ||
102 isa<ClassTemplateSpecializationDecl>(RD);
108 return !WantClassName && candidate.
isKeyword();
111 std::unique_ptr<CorrectionCandidateCallback> clone()
override {
112 return std::make_unique<TypeNameValidatorCCC>(*
this);
116 bool AllowInvalidDecl;
119 bool AllowNonTemplates;
131 case tok::kw___int64:
132 case tok::kw___int128:
134 case tok::kw_unsigned:
142 case tok::kw__Float16:
143 case tok::kw___float128:
144 case tok::kw___ibm128:
145 case tok::kw_wchar_t:
147 case tok::kw___underlying_type:
148 case tok::kw___auto_type:
151 case tok::annot_typename:
152 case tok::kw_char16_t:
153 case tok::kw_char32_t:
155 case tok::annot_decltype:
156 case tok::kw_decltype:
157 return getLangOpts().CPlusPlus;
159 case tok::kw_char8_t:
160 return getLangOpts().Char8;
170 enum class UnqualifiedTypeNameLookupResult {
181 static UnqualifiedTypeNameLookupResult
186 return UnqualifiedTypeNameLookupResult::NotFound;
188 UnqualifiedTypeNameLookupResult FoundTypeDecl =
189 UnqualifiedTypeNameLookupResult::NotFound;
192 if (
auto *BaseTT =
Base.getType()->getAs<
TagType>())
193 BaseRD = BaseTT->getAsCXXRecordDecl();
197 if (!TST || !TST->isDependentType())
199 auto *TD = TST->getTemplateName().getAsTemplateDecl();
202 if (
auto *BasePrimaryTemplate =
203 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
205 BaseRD = BasePrimaryTemplate;
206 else if (
auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208 CTD->findPartialSpecialization(
Base.getType()))
216 if (!isa<TypeDecl>(ND))
217 return UnqualifiedTypeNameLookupResult::FoundNonType;
218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222 case UnqualifiedTypeNameLookupResult::FoundNonType:
223 return UnqualifiedTypeNameLookupResult::FoundNonType;
224 case UnqualifiedTypeNameLookupResult::FoundType:
225 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227 case UnqualifiedTypeNameLookupResult::NotFound:
234 return FoundTypeDecl;
242 UnqualifiedTypeNameLookupResult FoundTypeDecl =
243 UnqualifiedTypeNameLookupResult::NotFound;
245 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246 DC = DC->getParent()) {
249 RD = dyn_cast<CXXRecordDecl>(DC);
253 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259 S.
Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
287 bool isClassName,
bool HasTrailingDot,
289 bool IsCtorOrDtorName,
290 bool WantNontrivialTypeSourceInfo,
291 bool IsClassTemplateDeductionContext,
294 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296 !isClassName && !HasTrailingDot;
303 LookupCtx = computeDeclContext(ObjectType);
305 LookupCtx = computeDeclContext(*SS,
false);
308 if (isDependentScopeSpecifier(*SS)) {
318 if (!isClassName && !IsCtorOrDtorName)
323 if (WantNontrivialTypeSourceInfo)
324 return ActOnTypenameType(S,
SourceLocation(), *SS, II, NameLoc).get();
336 RequireCompleteDeclContext(*SS, LookupCtx))
350 LookupQualifiedName(Result, LookupCtx);
352 if (ObjectTypePtr && Result.empty()) {
359 LookupName(Result, S);
363 LookupName(Result, S);
367 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->
isEmpty())) {
376 switch (Result.getResultKind()) {
380 TypeNameValidatorCCC CCC(
true, isClassName,
381 AllowDeducedTemplate);
383 S, SS, CCC, CTK_ErrorRecovery);
386 bool MemberOfUnknownSpecialization;
395 if (Correction && (NNS || NewII != &II) &&
400 isTemplateName(S, *NewSSPtr,
false,
TemplateName,
nullptr,
false,
401 Template, MemberOfUnknownSpecialization))) {
403 isClassName, HasTrailingDot, ObjectTypePtr,
405 WantNontrivialTypeSourceInfo,
406 IsClassTemplateDeductionContext);
408 diagnoseTypo(Correction,
409 PDiag(diag::err_unknown_type_or_class_name_suggest)
410 << Result.getLookupName() << isClassName);
413 *CorrectedII = NewII;
422 Result.suppressDiagnostics();
432 Result.suppressDiagnostics();
438 Res != ResEnd; ++Res) {
440 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
447 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
459 Result.suppressDiagnostics();
470 IIDecl = Result.getFoundDecl();
471 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
475 assert(IIDecl &&
"Didn't find decl");
478 if (
TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
482 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485 FoundRD->isInjectedClassName() &&
487 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
490 DiagnoseUseOfDecl(IIDecl, NameLoc);
493 MarkAnyDeclReferenced(TD->getLocation(), TD,
false);
495 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
498 FoundUsingShadow =
nullptr;
499 }
else if (
auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500 (void)DiagnoseUseOfDecl(UD, NameLoc);
503 FoundUsingShadow =
nullptr;
504 }
else if (AllowDeducedTemplate) {
510 FoundUsingShadow =
nullptr;
516 Result.suppressDiagnostics();
520 if (FoundUsingShadow)
526 if (SS && SS->
isNotEmpty() && !IsCtorOrDtorName &&
527 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528 if (WantNontrivialTypeSourceInfo) {
531 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
533 T = getElaboratedType(
ETK_None, *SS, T);
537 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
539 T = getElaboratedType(
ETK_None, *SS, T);
551 auto *ND = dyn_cast<NamespaceDecl>(DC);
552 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
554 else if (
auto *RD = dyn_cast<CXXRecordDecl>(DC))
556 RD->getTypeForDecl());
557 else if (isa<TranslationUnitDecl>(DC))
560 llvm_unreachable(
"something isn't in TU scope?");
571 if (
const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572 if (MD->getParent()->hasAnyDependentBases())
580 bool IsTemplateTypeArg) {
581 assert(getLangOpts().MSVCCompat &&
"shouldn't be called in non-MSVC mode");
584 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
593 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
599 RD->getTypeForDecl());
603 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
623 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
634 LookupName(R, S,
false);
638 switch (TD->getTagKind()) {
665 if (CurContext->isRecord()) {
675 return S->isFunctionPrototypeScope();
677 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
685 bool IsTemplateName) {
690 SuggestedType =
nullptr;
694 TypeNameValidatorCCC CCC(
false,
false,
699 CCC, CTK_ErrorRecovery)) {
701 bool CanRecover = !IsTemplateName;
702 if (Corrected.isKeyword()) {
704 diagnoseTypo(Corrected,
705 PDiag(IsTemplateName ? diag::err_no_template_suggest
706 : diag::err_unknown_typename_suggest)
708 II = Corrected.getCorrectionAsIdentifierInfo();
711 if (!SS || !SS->
isSet()) {
712 diagnoseTypo(Corrected,
713 PDiag(IsTemplateName ? diag::err_no_template_suggest
714 : diag::err_unknown_typename_suggest)
716 }
else if (
DeclContext *DC = computeDeclContext(*SS,
false)) {
717 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719 II->
getName().equals(CorrectedStr);
720 diagnoseTypo(Corrected,
722 ? diag::err_no_member_template_suggest
723 : diag::err_unknown_nested_typename_suggest)
724 << II << DC << DroppedSpecifier << SS->
getRange(),
727 llvm_unreachable(
"could not have corrected a typo here");
734 if (Corrected.getCorrectionSpecifier())
735 tmpSS.
MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740 tmpSS.
isSet() ? &tmpSS : SS,
false,
false,
nullptr,
747 if (getLangOpts().
CPlusPlus && !IsTemplateName) {
750 Name.setIdentifier(II, IILoc);
753 bool MemberOfUnknownSpecialization;
754 if (isTemplateName(S, SS ? *SS : EmptySS,
false,
755 Name,
nullptr,
true, TemplateResult,
757 diagnoseMissingTemplateArguments(TemplateResult.
get(), IILoc);
766 Diag(IILoc, IsTemplateName ? diag::err_no_template
767 : diag::err_unknown_typename)
769 else if (
DeclContext *DC = computeDeclContext(*SS,
false))
770 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771 : diag::err_typename_nested_not_found)
776 }
else if (isDependentScopeSpecifier(*SS)) {
777 unsigned DiagID = diag::err_typename_missing;
778 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779 DiagID = diag::ext_typename_missing;
786 *SS, *II, IILoc).
get();
789 "Invalid scope specifier has already been diagnosed");
797 NextToken.
is(tok::less);
800 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
803 if (CheckTemplate && isa<TemplateDecl>(*I))
817 StringRef FixItTagName;
818 switch (Tag->getTagKind()) {
820 FixItTagName =
"class ";
824 FixItTagName =
"enum ";
828 FixItTagName =
"struct ";
832 FixItTagName =
"__interface ";
836 FixItTagName =
"union ";
840 StringRef TagName = FixItTagName.drop_back();
841 SemaRef.
Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842 << Name << TagName << SemaRef.
getLangOpts().CPlusPlus
847 SemaRef.
Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
862 const Token &NextToken,
867 assert(NextToken.
isNot(tok::coloncolon) &&
868 "parse nested name specifiers before calling ClassifyName");
870 isCurrentClassName(*Name, S, &SS)) {
878 LookupResult Result(*
this, Name, NameLoc, LookupOrdinaryName);
879 LookupParsedName(Result, S, &SS, !CurMethod);
886 if (Result.empty() && SS.
isEmpty() && getLangOpts().MSVCCompat) {
897 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
901 return NameClassification::NonType(cast<NamedDecl>(Ivar.
get()));
905 LookupBuiltin(Result);
908 bool SecondTry =
false;
909 bool IsFilteredTemplateName =
false;
912 switch (Result.getResultKind()) {
916 if (SS.
isEmpty() && NextToken.
is(tok::l_paren)) {
920 return NameClassification::UndeclaredNonType();
934 if (
NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935 return NameClassification::NonType(D);
945 return NameClassification::UndeclaredTemplate(Template);
951 if (!getLangOpts().
CPlusPlus && !SecondTry &&
958 if (!SecondTry && CCC) {
961 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962 &SS, *CCC, CTK_ErrorRecovery)) {
963 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964 unsigned QualifiedDiag = diag::err_no_member_suggest;
966 NamedDecl *FirstDecl = Corrected.getFoundDecl();
967 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968 if (getLangOpts().
CPlusPlus && NextToken.
is(tok::less) &&
969 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970 UnqualifiedDiag = diag::err_no_template_suggest;
971 QualifiedDiag = diag::err_no_member_template_suggest;
972 }
else if (UnderlyingFirstDecl &&
973 (isa<TypeDecl>(UnderlyingFirstDecl) ||
974 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976 UnqualifiedDiag = diag::err_unknown_typename_suggest;
977 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
981 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985 Name->getName().equals(CorrectedStr);
986 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987 << Name << computeDeclContext(SS,
false)
988 << DroppedSpecifier << SS.
getRange());
992 Name = Corrected.getCorrectionAsIdentifierInfo();
995 if (Corrected.isKeyword())
1001 Result.setLookupName(Corrected.getCorrection());
1003 Result.addDecl(FirstDecl);
1011 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1015 return NameClassification::NonType(Ivar);
1023 Result.suppressDiagnostics();
1041 return NameClassification::DependentNonType();
1050 if (getLangOpts().
CPlusPlus && NextToken.
is(tok::less) &&
1051 hasAnyAcceptableTemplateNames(Result,
true,
1064 FilterAcceptableTemplateNames(Result);
1065 if (!Result.isAmbiguous()) {
1066 IsFilteredTemplateName =
true;
1075 if (getLangOpts().
CPlusPlus && NextToken.
is(tok::less) &&
1076 (IsFilteredTemplateName ||
1077 hasAnyAcceptableTemplateNames(
1092 if (!IsFilteredTemplateName)
1093 FilterAcceptableTemplateNames(Result);
1095 bool IsFunctionTemplate;
1098 if (Result.end() - Result.begin() > 1) {
1099 IsFunctionTemplate =
true;
1102 }
else if (!Result.empty()) {
1103 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104 *Result.begin(),
true,
1106 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107 IsVarTemplate = isa<VarTemplateDecl>(TD);
1118 IsFunctionTemplate =
true;
1122 if (IsFunctionTemplate) {
1126 Result.suppressDiagnostics();
1128 return NameClassification::FunctionTemplate(Template);
1131 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132 : NameClassification::TypeTemplate(Template);
1137 if (
const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1144 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145 T = getElaboratedType(
ETK_None, SS, T);
1149 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1154 DiagnoseUseOfDecl(
Type, NameLoc);
1155 MarkAnyDeclReferenced(
Type->getLocation(),
Type,
false);
1156 return BuildTypeFor(
Type, *Result.begin());
1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164 Class = Alias->getClassInterface();
1168 DiagnoseUseOfDecl(Class, NameLoc);
1170 if (NextToken.
is(tok::period)) {
1173 Result.suppressDiagnostics();
1181 if (isa<ConceptDecl>(FirstDecl))
1182 return NameClassification::Concept(
1185 if (
auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1191 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192 !isa<VarTemplateDecl>(FirstDecl))
1193 return NameClassification::TypeTemplate(
1198 bool NextIsOp = NextToken.
isOneOf(tok::amp, tok::star);
1199 if ((NextToken.
is(tok::identifier) ||
1204 DiagnoseUseOfDecl(
Type, NameLoc);
1205 return BuildTypeFor(
Type, *Result.begin());
1212 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.
is(tok::l_paren));
1214 return NameClassification::NonType(Result.getRepresentativeDecl());
1217 Result.suppressDiagnostics();
1220 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221 Result.begin(), Result.end()));
1227 assert(getLangOpts().
CPlusPlus &&
"ADL-only call in C?");
1229 LookupResult Result(*
this, Name, NameLoc, LookupOrdinaryName);
1230 return BuildDeclarationNameExpr(SS, Result,
true);
1237 bool IsAddressOfOperand) {
1240 NameInfo, IsAddressOfOperand,
1247 const Token &NextToken) {
1248 if (getCurMethodDecl() && SS.
isEmpty())
1250 return BuildIvarRefExpr(S, NameLoc, Ivar);
1254 Result.addDecl(Found);
1255 Result.resolveKind();
1257 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.
is(tok::l_paren));
1258 return BuildDeclarationNameExpr(SS, Result, ADL);
1264 auto *ULE = cast<UnresolvedLookupExpr>(E);
1265 if ((*ULE->decls_begin())->isCXXClassMember()) {
1267 SS.
Adopt(ULE->getQualifierLoc());
1270 LookupResult Result(*
this, ULE->getName(), ULE->getNameLoc(),
1271 LookupOrdinaryName);
1272 Result.setNamingClass(ULE->getNamingClass());
1273 for (
auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274 Result.addDecl(*I, I.getAccess());
1275 Result.resolveKind();
1276 return BuildPossibleImplicitMemberExpr(SS,
SourceLocation(), Result,
1287 auto *TD = Name.getAsTemplateDecl();
1289 return TemplateNameKindForDiagnostics::DependentTemplate;
1290 if (isa<ClassTemplateDecl>(TD))
1291 return TemplateNameKindForDiagnostics::ClassTemplate;
1292 if (isa<FunctionTemplateDecl>(TD))
1293 return TemplateNameKindForDiagnostics::FunctionTemplate;
1294 if (isa<VarTemplateDecl>(TD))
1295 return TemplateNameKindForDiagnostics::VarTemplate;
1296 if (isa<TypeAliasTemplateDecl>(TD))
1297 return TemplateNameKindForDiagnostics::AliasTemplate;
1298 if (isa<TemplateTemplateParmDecl>(TD))
1299 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300 if (isa<ConceptDecl>(TD))
1301 return TemplateNameKindForDiagnostics::Concept;
1302 return TemplateNameKindForDiagnostics::DependentTemplate;
1307 "The next DeclContext should be lexically contained in the current one.");
1313 assert(CurContext &&
"DeclContext imbalance!");
1315 CurContext = CurContext->getLexicalParent();
1316 assert(CurContext &&
"Popped translation unit!");
1325 CurContext = cast<TagDecl>(D)->getDefinition();
1326 assert(CurContext &&
"skipping definition of undefined tag");
1329 S->setEntity(CurContext->getLookupParent());
1334 CurContext =
static_cast<decltype(CurContext)
>(Context);
1357 assert(!S->getEntity() &&
"scope already has entity");
1360 Scope *Ancestor = S->getParent();
1362 assert(Ancestor->
getEntity() == CurContext &&
"ancestor context mismatch");
1368 if (S->getParent()->isTemplateParamScope()) {
1371 EnterTemplatedContext(S->getParent(), DC);
1376 assert(S->getEntity() == CurContext &&
"Context imbalance!");
1380 Scope *Ancestor = S->getParent();
1389 assert(S->isTemplateParamScope() &&
1390 "expected to be initializing a template parameter scope");
1413 unsigned ScopeDepth = getTemplateDepth(S);
1414 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1418 cast<Decl>(DC)->getDescribedTemplateParams()) {
1419 unsigned DCDepth = TPL->getDepth() + 1;
1420 if (DCDepth > ScopeDepth)
1422 if (ScopeDepth == DCDepth)
1427 S->setLookupEntity(SearchDCAfterScope);
1441 "The next DeclContext should be lexically contained in the current one.");
1443 S->setEntity(CurContext);
1445 for (
unsigned P = 0, NumParams = FD->
getNumParams();
P < NumParams; ++
P) {
1450 IdResolver.AddDecl(Param);
1458 assert(CurContext &&
"DeclContext imbalance!");
1459 CurContext = CurContext->getLexicalParent();
1460 assert(CurContext &&
"Popped translation unit!");
1489 return ND->
hasAttr<OverloadableAttr>();
1492 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1502 while (S->getEntity() && S->getEntity()->isTransparentContext())
1509 CurContext->addDecl(D);
1517 if (isa<FunctionDecl>(D) &&
1518 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1523 IEnd = IdResolver.end();
1524 for (; I != IEnd; ++I) {
1527 IdResolver.RemoveDecl(*I);
1536 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1540 for (I = IdResolver.begin(D->
getDeclName()); I != IEnd; ++I) {
1542 if (IDC == CurContext) {
1543 if (!S->isDeclScope(*I))
1545 }
else if (IDC->
Encloses(CurContext))
1549 IdResolver.InsertDeclAfter(I, D);
1551 IdResolver.AddDecl(D);
1553 warnOnReservedIdentifier(D);
1557 bool AllowInlineNamespace) {
1558 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1565 if (ScopeDC->getPrimaryContext() == TargetDC)
1567 }
while ((S = S->getParent()));
1579 bool ConsiderLinkage,
1580 bool AllowInlineNamespace) {
1585 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1610 makeMergedDefinitionVisible(New);
1635 if (NewIsModuleInterface || OldIsModuleInterface) {
1641 << NewIsModuleInterface
1643 << OldIsModuleInterface
1674 if (!IsNewExported && !IsOldExported)
1680 assert(IsNewExported);
1682 Diag(New->
getLocation(), diag::err_redeclaration_non_exported) << New;
1690 if (CheckRedeclarationModuleOwnership(New, Old))
1693 if (CheckRedeclarationExported(New, Old))
1700 return isa<UsingShadowDecl>(D) ||
1701 isa<UnresolvedUsingTypenameDecl>(D) ||
1702 isa<UnresolvedUsingValueDecl>(D);
1729 return CD->isCopyConstructor();
1745 bool Sema::mightHaveNonExternalLinkage(
const DeclaratorDecl *D) {
1748 if (
const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1749 if (!RD->hasNameForLinkage())
1778 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1784 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1787 if (
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1792 if (FD->isInlined() && !
isMainFileLoc(*
this, FD->getLocation()))
1796 if (FD->doesThisDeclarationHaveABody() &&
1799 }
else if (
const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1809 if (VD->isStaticDataMember() &&
1812 if (VD->isStaticDataMember() &&
1814 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1817 if (VD->isInline() && !
isMainFileLoc(*
this, VD->getLocation()))
1826 return mightHaveNonExternalLinkage(D);
1833 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1835 if (FD !=
First && ShouldWarnIfUnusedFileScopedDecl(
First))
1839 if (
const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1841 if (VD !=
First && ShouldWarnIfUnusedFileScopedDecl(
First))
1845 if (ShouldWarnIfUnusedFileScopedDecl(D))
1846 UnusedFileScopedDecls.push_back(D);
1853 if (
auto *DD = dyn_cast<DecompositionDecl>(D)) {
1857 for (
auto *BD : DD->bindings())
1858 if (BD->isReferenced())
1866 if (D->
hasAttr<UnusedAttr>() || D->
hasAttr<ObjCPreciseLifetimeAttr>())
1869 if (isa<LabelDecl>(D))
1875 if (
const auto *R = dyn_cast<CXXRecordDecl>(D->
getDeclContext()))
1878 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1879 if (!WithinFunction)
1882 if (isa<TypedefNameDecl>(D))
1886 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1890 if (
const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1893 const auto *Ty = VD->getType().getTypePtr();
1897 if (TT->getDecl()->hasAttr<UnusedAttr>())
1903 if (Ty->isIncompleteType() || Ty->isDependentType())
1908 Ty = Ty->getBaseElementTypeUnsafe();
1911 const TagDecl *Tag = TT->getDecl();
1912 if (Tag->
hasAttr<UnusedAttr>())
1915 if (
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1916 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1919 if (
const Expr *Init = VD->getInit()) {
1921 dyn_cast<ExprWithCleanups>(Init))
1922 Init = Cleanups->getSubExpr();
1924 dyn_cast<CXXConstructExpr>(Init);
1927 if (!CD->
isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1928 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1934 if (Init->isTypeDependent())
1936 if (!Ctor->isTrivial())
1950 if (isa<LabelDecl>(D)) {
1965 for (
auto *TmpD : D->
decls()) {
1966 if (
const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1967 DiagnoseUnusedDecl(T);
1968 else if(
const auto *R = dyn_cast<RecordDecl>(TmpD))
1969 DiagnoseUnusedNestedTypedefs(R);
1979 if (
auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1982 UnusedLocalTypedefNameCandidates.insert(TD);
1990 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1991 DiagID = diag::warn_unused_exception_param;
1992 else if (isa<LabelDecl>(D))
1993 DiagID = diag::warn_unused_label;
1995 DiagID = diag::warn_unused_variable;
2009 if (Ty->isReferenceType() || Ty->isDependentType())
2013 const TagDecl *Tag = TT->getDecl();
2014 if (Tag->
hasAttr<UnusedAttr>())
2018 if (
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2019 if (!RD->hasAttr<WarnUnusedAttr>())
2027 if (VD->
hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2033 if (VD->
hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2036 auto iter = RefsMinusAssignments.find(VD);
2037 if (iter == RefsMinusAssignments.end())
2040 assert(iter->getSecond() >= 0 &&
2041 "Found a negative number of references to a VarDecl");
2042 if (iter->getSecond() != 0)
2044 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2045 : diag::warn_unused_but_set_variable;
2054 bool Diagnose =
false;
2058 Diagnose = L->
getStmt() ==
nullptr;
2064 S->mergeNRVOIntoParent();
2066 if (S->decl_empty())
return;
2068 "Scope shouldn't contain decls!");
2070 for (
auto *TmpD : S->decls()) {
2071 assert(TmpD &&
"This decl didn't get pushed??");
2073 assert(isa<NamedDecl>(TmpD) &&
"Decl isn't NamedDecl?");
2077 if (!S->hasUnrecoverableErrorOccurred()) {
2078 DiagnoseUnusedDecl(D);
2079 if (
const auto *RD = dyn_cast<RecordDecl>(D))
2080 DiagnoseUnusedNestedTypedefs(RD);
2081 if (
VarDecl *VD = dyn_cast<VarDecl>(D)) {
2082 DiagnoseUnusedButSetDecl(VD);
2083 RefsMinusAssignments.erase(VD);
2090 if (
LabelDecl *LD = dyn_cast<LabelDecl>(D))
2095 IdResolver.RemoveDecl(D);
2096 auto ShadowI = ShadowingDecls.find(D);
2097 if (ShadowI != ShadowingDecls.end()) {
2098 if (
const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2100 << D << FD << FD->getParent();
2101 Diag(FD->getLocation(), diag::note_previous_declaration);
2103 ShadowingDecls.erase(ShadowI);
2123 bool DoTypoCorrection) {
2126 NamedDecl *IDecl = LookupSingleName(TUScope,
Id, IdLoc, LookupOrdinaryName);
2128 if (!IDecl && DoTypoCorrection) {
2134 TUScope,
nullptr, CCC, CTK_ErrorRecovery)) {
2135 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) <<
Id);
2172 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2173 (S->isClassScope() && !getLangOpts().
CPlusPlus))
2190 return "ucontext.h";
2192 llvm_unreachable(
"unhandled error kind");
2203 Parent->addDecl(CLinkageDecl);
2209 getCurFPFeatures().isFPConstrained(),
2212 New->
addAttr(BuiltinAttr::CreateImplicit(Context,
ID));
2218 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2221 FT->getParamType(i),
nullptr,
SC_None,
nullptr);
2223 Params.push_back(parm);
2225 New->setParams(Params);
2228 AddKnownFunctionAttributes(New);
2237 Scope *S,
bool ForRedeclaration,
2239 LookupNecessaryTypesForBuiltin(S,
ID);
2244 if (!ForRedeclaration)
2256 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2263 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2269 if (!ForRedeclaration &&
2272 Diag(Loc, diag::ext_implicit_lib_function_decl)
2275 Diag(Loc, diag::note_include_header_or_declare)
2283 RegisterLocallyScopedExternCDecl(New, S);
2291 PushOnScopeChains(New, TUScope);
2292 CurContext = SavedContext;
2312 while (
Filter.hasNext()) {
2321 if (
auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2323 Decl->getUnderlyingType()))
2328 if (OldTD->getAnonDeclWithTypedefName(
true) &&
2329 Decl->getAnonDeclWithTypedefName())
2342 OldType = OldTypedef->getUnderlyingType();
2349 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2350 Diag(New->
getLocation(), diag::err_redefinition_variably_modified_typedef)
2358 if (OldType != NewType &&
2362 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2364 <<
Kind << NewType << OldType;
2386 if (getLangOpts().ObjC) {
2388 switch (
TypeID->getLength()) {
2392 if (!
TypeID->isStr(
"id"))
2408 if (!
TypeID->isStr(
"Class"))
2415 if (!
TypeID->isStr(
"SEL"))
2442 if (
auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2443 auto *OldTag = OldTD->getAnonDeclWithTypedefName(
true);
2446 if (OldTag && NewTag &&
2447 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2448 !hasVisibleDefinition(OldTag, &Hidden)) {
2452 if (OldTD->isModed())
2454 OldTD->getUnderlyingType());
2459 makeMergedDefinitionVisible(Hidden);
2463 if (isa<EnumDecl>(NewTag)) {
2464 Scope *EnumScope = getNonFieldDeclScope(S);
2465 for (
auto *D : NewTag->decls()) {
2466 auto *ED = cast<EnumConstantDecl>(D);
2469 IdResolver.RemoveDecl(ED);
2470 ED->getLexicalDeclContext()->removeDecl(ED);
2478 if (isIncompatibleTypedef(Old, New))
2485 mergeDeclAttributes(New, Old);
2488 if (getLangOpts().MicrosoftExt)
2496 if (!isa<CXXRecordDecl>(CurContext))
2520 if (!isa<TypedefNameDecl>(Old))
2530 if (getLangOpts().Modules || getLangOpts().
C11)
2537 if (getDiagnostics().getSuppressSystemWarnings() &&
2552 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2553 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2554 for (
const auto *i : D->
attrs())
2555 if (i->getKind() == A->
getKind()) {
2557 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2562 if (OA && isa<OwnershipAttr>(i))
2563 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2571 if (
VarDecl *VD = dyn_cast<VarDecl>(D))
2572 return VD->isThisDeclarationADefinition();
2573 if (
TagDecl *TD = dyn_cast<TagDecl>(D))
2574 return TD->isCompleteDefinition() || TD->isBeingDefined();
2585 AlignedAttr *OldAlignasAttr =
nullptr;
2586 AlignedAttr *OldStrictestAlignAttr =
nullptr;
2587 unsigned OldAlign = 0;
2595 if (I->isAlignmentDependent())
2601 unsigned Align = I->getAlignment(S.
Context);
2602 if (Align > OldAlign) {
2604 OldStrictestAlignAttr = I;
2609 AlignedAttr *NewAlignasAttr =
nullptr;
2610 unsigned NewAlign = 0;
2612 if (I->isAlignmentDependent())
2618 unsigned Align = I->getAlignment(S.
Context);
2619 if (Align > NewAlign)
2623 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2631 if (OldAlign == 0 || NewAlign == 0) {
2633 if (
ValueDecl *VD = dyn_cast<ValueDecl>(New))
2644 if (OldAlign != NewAlign) {
2645 S.
Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2648 S.
Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2663 S.
Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2667 bool AnyAdded =
false;
2670 if (OldAlign > NewAlign) {
2671 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.
Context);
2672 Clone->setInherited(
true);
2678 if (OldAlignasAttr && !NewAlignasAttr &&
2679 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2680 AlignedAttr *Clone = OldAlignasAttr->clone(S.
Context);
2681 Clone->setInherited(
true);
2689 #define WANT_DECL_MERGE_LOGIC
2690 #include "clang/Sema/AttrParsedAttrImpl.inc"
2691 #undef WANT_DECL_MERGE_LOGIC
2698 if (!DiagnoseMutualExclusions(S, D,
Attr))
2709 if (
const auto *AA = dyn_cast<AvailabilityAttr>(
Attr))
2711 D, *AA, AA->getPlatform(), AA->
isImplicit(), AA->getIntroduced(),
2712 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2713 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2715 else if (
const auto *VA = dyn_cast<VisibilityAttr>(
Attr))
2717 else if (
const auto *VA = dyn_cast<TypeVisibilityAttr>(
Attr))
2719 else if (
const auto *ImportA = dyn_cast<DLLImportAttr>(
Attr))
2721 else if (
const auto *ExportA = dyn_cast<DLLExportAttr>(
Attr))
2723 else if (
const auto *EA = dyn_cast<ErrorAttr>(
Attr))
2725 else if (
const auto *FA = dyn_cast<FormatAttr>(
Attr))
2726 NewAttr = S.
mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2728 else if (
const auto *SA = dyn_cast<SectionAttr>(
Attr))
2730 else if (
const auto *CSA = dyn_cast<CodeSegAttr>(
Attr))
2732 else if (
const auto *IA = dyn_cast<MSInheritanceAttr>(
Attr))
2734 IA->getInheritanceModel());
2735 else if (
const auto *AA = dyn_cast<AlwaysInlineAttr>(
Attr))
2738 else if (S.
getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2739 (isa<CUDAHostAttr>(
Attr) || isa<CUDADeviceAttr>(
Attr) ||
2740 isa<CUDAGlobalAttr>(
Attr))) {
2744 }
else if (
const auto *MA = dyn_cast<MinSizeAttr>(
Attr))
2746 else if (
const auto *SNA = dyn_cast<SwiftNameAttr>(
Attr))
2748 else if (
const auto *OA = dyn_cast<OptimizeNoneAttr>(
Attr))
2750 else if (
const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(
Attr))
2752 else if (isa<AlignedAttr>(
Attr))
2756 else if ((isa<DeprecatedAttr>(
Attr) || isa<UnavailableAttr>(
Attr)) &&
2761 else if (
const auto *UA = dyn_cast<UuidAttr>(
Attr))
2762 NewAttr = S.
mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2763 else if (
const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(
Attr))
2765 else if (
const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(
Attr))
2767 else if (
const auto *A = dyn_cast<SYCLIntelLoopFuseAttr>(
Attr))
2769 else if (
const auto *TCBA = dyn_cast<EnforceTCBAttr>(
Attr))
2771 else if (
const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(
Attr))
2773 else if (
const auto *A = dyn_cast<IntelReqdSubGroupSizeAttr>(
Attr))
2775 else if (
const auto *A = dyn_cast<IntelNamedSubGroupSizeAttr>(
Attr))
2777 else if (
const auto *A = dyn_cast<SYCLIntelNumSimdWorkItemsAttr>(
Attr))
2779 else if (
const auto *A = dyn_cast<SYCLIntelESimdVectorizeAttr>(
Attr))
2781 else if (
const auto *A = dyn_cast<SYCLIntelSchedulerTargetFmaxMhzAttr>(
Attr))
2783 else if (
const auto *A = dyn_cast<SYCLIntelNoGlobalWorkOffsetAttr>(
Attr))
2785 else if (
const auto *A = dyn_cast<IntelFPGAMaxReplicatesAttr>(
Attr))
2787 else if (
const auto *A = dyn_cast<SYCLIntelFPGAMaxConcurrencyAttr>(
Attr))
2789 else if (
const auto *A = dyn_cast<IntelFPGAForcePow2DepthAttr>(
Attr))
2791 else if (
const auto *A = dyn_cast<SYCLIntelFPGAInitiationIntervalAttr>(
Attr))
2793 else if (
const auto *A = dyn_cast<WorkGroupSizeHintAttr>(
Attr))
2795 else if (
const auto *A = dyn_cast<SYCLIntelMaxGlobalWorkDimAttr>(
Attr))
2797 else if (
const auto *BTFA = dyn_cast<BTFDeclTagAttr>(
Attr))
2799 else if (
const auto *A = dyn_cast<IntelFPGABankWidthAttr>(
Attr))
2801 else if (
const auto *A = dyn_cast<IntelFPGANumBanksAttr>(
Attr))
2803 else if (
const auto *A = dyn_cast<SYCLDeviceHasAttr>(
Attr))
2805 else if (
const auto *A = dyn_cast<SYCLUsesAspectsAttr>(
Attr))
2807 else if (
const auto *A = dyn_cast<SYCLIntelPipeIOAttr>(
Attr))
2809 else if (
const auto *A = dyn_cast<SYCLIntelMaxWorkGroupSizeAttr>(
Attr))
2811 else if (
const auto *A = dyn_cast<SYCLAddIRAttributesFunctionAttr>(
Attr))
2813 else if (
const auto *A =
2814 dyn_cast<SYCLAddIRAttributesKernelParameterAttr>(
Attr))
2816 else if (
const auto *A =
2817 dyn_cast<SYCLAddIRAttributesGlobalVariableAttr>(
Attr))
2819 else if (
const auto *A = dyn_cast<ReqdWorkGroupSizeAttr>(
Attr))
2827 if (isa<MSInheritanceAttr>(NewAttr))
2836 if (
const TagDecl *TD = dyn_cast<TagDecl>(D))
2837 return TD->getDefinition();
2838 if (
const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2844 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2846 if (FD->isDefined(Def,
true))
2853 for (
const auto *Attribute : D->
attrs())
2854 if (Attribute->getKind() ==
Kind)
2866 if (!Def || Def == New)
2870 for (
unsigned I = 0, E = NewAttributes.size(); I != E;) {
2871 const Attr *NewAttribute = NewAttributes[I];
2873 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2880 NewAttributes.erase(NewAttributes.begin() + I);
2885 VarDecl *VD = cast<VarDecl>(New);
2886 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2888 ? diag::err_alias_after_tentative
2889 : diag::err_redefinition;
2891 if (
Diag == diag::err_redefinition)
2901 if (
const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2914 if (isa<C11NoReturnAttr>(NewAttribute)) {
2918 }
else if (isa<UuidAttr>(NewAttribute)) {
2922 }
else if (
const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2923 if (AA->isAlignas()) {
2934 S.
Diag(NewAttribute->
getLocation(), diag::note_alignas_on_declaration)
2936 NewAttributes.erase(NewAttributes.begin() + I);
2940 }
else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2946 diag::err_loader_uninitialized_redeclaration);
2948 NewAttributes.erase(NewAttributes.begin() + I);
2952 }
else if (isa<SelectAnyAttr>(NewAttribute) &&
2953 cast<VarDecl>(New)->isInline() &&
2954 !cast<VarDecl>(New)->isInlineSpecified()) {
2961 }
else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2969 diag::warn_attribute_precede_definition);
2971 NewAttributes.erase(NewAttributes.begin() + I);
2977 const ConstInitAttr *CIAttr,
2978 bool AttrBeforeInit) {
2989 if (SuitableSpelling.empty() && S.
getLangOpts().CPlusPlus11)
2991 InsertLoc, {tok::l_square, tok::l_square,
2992 S.PP.getIdentifierInfo(
"clang"), tok::coloncolon,
2993 S.PP.getIdentifierInfo(
"require_constant_initialization"),
2994 tok::r_square, tok::r_square}));
2995 if (SuitableSpelling.empty())
2997 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2998 S.PP.getIdentifierInfo(
"require_constant_initialization"),
2999 tok::r_paren, tok::r_paren}));
3000 if (SuitableSpelling.empty() && S.
getLangOpts().CPlusPlus20)
3001 SuitableSpelling =
"constinit";
3002 if (SuitableSpelling.empty() && S.
getLangOpts().CPlusPlus11)
3003 SuitableSpelling =
"[[clang::require_constant_initialization]]";
3004 if (SuitableSpelling.empty())
3005 SuitableSpelling =
"__attribute__((require_constant_initialization))";
3006 SuitableSpelling +=
" ";
3008 if (AttrBeforeInit) {
3011 assert(CIAttr->isConstinit() &&
"should not diagnose this for attribute");
3014 S.
Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3018 S.
Diag(CIAttr->getLocation(),
3019 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3020 : diag::warn_require_const_init_added_too_late)
3023 << CIAttr->isConstinit()
3032 UsedAttr *NewAttr = OldAttr->clone(Context);
3033 NewAttr->setInherited(
true);
3037 RetainAttr *NewAttr = OldAttr->clone(Context);
3038 NewAttr->setInherited(
true);
3048 const auto *OldConstInit = Old->
getAttr<ConstInitAttr>();
3049 const auto *NewConstInit = New->
getAttr<ConstInitAttr>();
3050 if (
bool(OldConstInit) !=
bool(NewConstInit)) {
3051 const auto *OldVD = cast<VarDecl>(Old);
3052 auto *NewVD = cast<VarDecl>(New);
3058 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3061 if (InitDecl == NewVD) {
3065 if (OldConstInit && OldConstInit->isConstinit())
3068 }
else if (NewConstInit) {
3072 if (InitDecl && InitDecl != NewVD) {
3075 NewVD->dropAttr<ConstInitAttr>();
3083 if (AsmLabelAttr *NewA = New->
getAttr<AsmLabelAttr>()) {
3084 if (AsmLabelAttr *OldA = Old->
getAttr<AsmLabelAttr>()) {
3085 if (!OldA->isEquivalent(NewA)) {
3088 Diag(OldA->getLocation(), diag::note_previous_declaration);
3090 }
else if (Old->
isUsed()) {
3094 << isa<FunctionDecl>(Old) << New->
getAttr<AsmLabelAttr>()->getRange();
3099 if (
const auto *NewAbiTagAttr = New->
getAttr<AbiTagAttr>()) {
3100 if (
const auto *OldAbiTagAttr = Old->
getAttr<AbiTagAttr>()) {
3101 for (
const auto &NewTag : NewAbiTagAttr->tags()) {
3102 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3103 Diag(NewAbiTagAttr->getLocation(),
3104 diag::err_new_abi_tag_on_redeclaration)
3106 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3110 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3116 if (New->
hasAttr<SectionAttr>() && !Old->
hasAttr<SectionAttr>()) {
3117 if (
auto *VD = dyn_cast<VarDecl>(New)) {
3119 Diag(New->
getLocation(), diag::warn_attribute_section_on_redeclaration);
3126 const auto *NewCSA = New->
getAttr<CodeSegAttr>();
3127 if (NewCSA && !Old->
hasAttr<CodeSegAttr>() &&
3128 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3146 if (isa<DeprecatedAttr>(I) ||
3147 isa<UnavailableAttr>(I) ||
3148 isa<AvailabilityAttr>(I)) {
3153 case AMK_Redeclaration:
3155 case AMK_ProtocolImplementation:
3156 case AMK_OptionalProtocolImplementation:
3163 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3185 const CarriesDependencyAttr *CDA = newDecl->
getAttr<CarriesDependencyAttr>();
3186 if (CDA && !oldDecl->
hasAttr<CarriesDependencyAttr>()) {
3187 S.
Diag(CDA->getLocation(),
3188 diag::err_carries_dependency_missing_on_first_decl) << 1;
3196 diag::note_carries_dependency_missing_first_decl) << 1;
3202 bool foundAny = newDecl->
hasAttrs();
3211 cast<InheritableParamAttr>(I->clone(S.
Context));
3226 if (*Oldnullability != *Newnullability) {
3227 S.
Diag(NewParam->
getLocation(), diag::warn_mismatched_nullability_attr)
3252 struct GNUCompatibleParamWarning {
3262 template <
typename T>
3263 static std::pair<diag::kind, SourceLocation>
3267 if (Old->isThisDeclarationADefinition())
3268 PrevDiag = diag::note_previous_definition;
3269 else if (Old->isImplicit()) {
3270 PrevDiag = diag::note_previous_implicit_declaration;
3272 OldLocation = New->getLocation();
3274 PrevDiag = diag::note_previous_declaration;
3275 return std::make_pair(PrevDiag, OldLocation);
3283 return ((FD->
hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3284 !LangOpts.CPlusPlus &&
3296 template <
typename T>
3310 template<
typename T>
static bool isExternC(T *D) {
return D->isExternC(); }
3317 template<
typename ExpectedDecl>
3339 !Old->getDeclContext()->getRedeclContext()->Equals(
3340 New->getDeclContext()->getRedeclContext()) &&
3345 S.
Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3358 const auto *AttrA = A->
getAttr<PassObjectSizeAttr>();
3359 const auto *AttrB = B->
getAttr<PassObjectSizeAttr>();
3362 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3363 AttrA->isDynamic() == AttrB->isDynamic();
3366 return std::equal(A->param_begin(), A->param_end(), B->
param_begin(), AttrEq);
3389 if (NamedDC->Equals(SemaDC))
3392 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3394 "unexpected context for redeclaration");
3405 if (
auto *FD = dyn_cast<FunctionDecl>(NewD))
3406 FixSemaDC(FD->getDescribedFunctionTemplate());
3407 else if (
auto *VD = dyn_cast<VarDecl>(NewD))
3408 FixSemaDC(VD->getDescribedVarTemplate());
3423 Scope *S,
bool MergeTypeWithOld) {
3430 Diag(Shadow->getTargetDecl()->getLocation(),
3431 diag::note_using_decl_target);
3432 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3441 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*
this, Shadow,
3444 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3447 if (checkUsingShadowRedecl<FunctionDecl>(*
this, Shadow, New))
3449 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3468 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3477 std::tie(PrevDiag, OldLocation) =
3484 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3489 if (getLangOpts().MicrosoftExt) {
3491 Diag(OldLocation, PrevDiag);
3494 Diag(OldLocation, PrevDiag);
3499 if (
const auto *ILA = New->
getAttr<InternalLinkageAttr>())
3500 if (!Old->
hasAttr<InternalLinkageAttr>()) {
3504 New->
dropAttr<InternalLinkageAttr>();
3507 if (
auto *EA = New->
getAttr<ErrorAttr>()) {
3508 if (!Old->
hasAttr<ErrorAttr>()) {
3509 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3515 if (CheckRedeclarationInModule(New, Old))
3518 if (!getLangOpts().CPlusPlus) {
3519 bool OldOvl = Old->
hasAttr<OverloadableAttr>();
3530 const Decl *DiagOld = Old;
3532 auto OldIter = llvm::find_if(Old->
redecls(), [](
const Decl *D) {
3533 const auto *A = D->getAttr<OverloadableAttr>();
3534 return A && !A->isImplicit();
3538 DiagOld = OldIter == Old->
redecls_end() ? nullptr : *OldIter;
3543 diag::note_attribute_overloadable_prev_overload)
3547 New->
addAttr(OverloadableAttr::CreateImplicit(Context));
3568 const FunctionType *OldType = cast<FunctionType>(OldQType);
3569 const FunctionType *NewType = cast<FunctionType>(NewQType);
3572 bool RequiresAdjustment =
false;
3574 if (OldTypeInfo.
getCC() != NewTypeInfo.
getCC()) {
3579 bool NewCCExplicit = getCallingConvAttributedType(New->
getType());
3580 if (!NewCCExplicit) {
3584 RequiresAdjustment =
true;
3594 << (
int)CallingConventionIgnoredReason::BuiltinFunction;
3596 RequiresAdjustment =
true;
3599 bool FirstCCExplicit = getCallingConvAttributedType(
First->getType());
3603 << (!FirstCCExplicit ?
"" :
3607 Diag(
First->getLocation(), diag::note_previous_declaration);
3615 RequiresAdjustment =
true;
3625 Diag(OldLocation, diag::note_previous_declaration);
3630 RequiresAdjustment =
true;
3637 <<
"'ns_returns_retained'";
3638 Diag(OldLocation, diag::note_previous_declaration);
3643 RequiresAdjustment =
true;
3649 AnyX86NoCallerSavedRegistersAttr *
Attr =
3650 New->
getAttr<AnyX86NoCallerSavedRegistersAttr>();
3652 Diag(OldLocation, diag::note_previous_declaration);
3657 RequiresAdjustment =
true;
3660 if (RequiresAdjustment) {
3670 !New->
hasAttr<GNUInlineAttr>() &&
3671 !getLangOpts().GNUInline &&
3679 if (New->
hasAttr<GNUInlineAttr>() &&
3690 Diag(OldLocation, PrevDiag) << Old << Old->
getType();
3705 if (CheckEquivalentExceptionSpec(Old, New))
3717 if (!Context.
hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3718 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3719 OldDeclaredReturnType)) {
3727 Diag(New->
getLocation(), diag::err_member_def_does_not_match_ret_type)
3732 Diag(OldLocation, PrevDiag) << Old << Old->
getType()
3741 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3742 if (OldReturnType != NewReturnType) {
3758 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3760 if (OldMethod && NewMethod) {
3767 bool IsClassScopeExplicitSpecialization =
3773 !IsClassScopeExplicitSpecialization) {
3779 Diag(OldLocation, PrevDiag) << Old << Old->
getType();
3787 if (!inTemplateInstantiation()) {
3789 if (isa<CXXConstructorDecl>(OldMethod))
3790 NewDiag = diag::err_constructor_redeclared;
3791 else if (isa<CXXDestructorDecl>(NewMethod))
3792 NewDiag = diag::err_destructor_redeclared;
3793 else if (isa<CXXConversionDecl>(NewMethod))
3794 NewDiag = diag::err_conv_function_redeclared;
3796 NewDiag = diag::err_member_redeclared;
3800 Diag(New->
getLocation(), diag::err_member_redeclared_in_instantiation)
3803 Diag(OldLocation, PrevDiag) << Old << Old->
getType();
3816 diag::err_definition_of_implicitly_declared_member)
3817 << New << getSpecialMember(OldMethod);
3822 diag::err_definition_of_explicitly_defaulted_member)
3823 << getSpecialMember(OldMethod);
3832 if (
const auto *NRA = New->
getAttr<CXX11NoReturnAttr>())
3833 if (!Old->
hasAttr<CXX11NoReturnAttr>()) {
3834 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3843 const CarriesDependencyAttr *CDA = New->
getAttr<CarriesDependencyAttr>();
3844 if (CDA && !Old->
hasAttr<CarriesDependencyAttr>()) {
3845 Diag(CDA->getLocation(),
3846 diag::err_carries_dependency_missing_on_first_decl) << 0;
3848 diag::note_carries_dependency_missing_first_decl) << 0;
3857 QualType OldQTypeForComparison = OldQType;
3862 OldQTypeForComparison =
QualType(OldTypeForComparison, 0);
3877 Diag(OldLocation, PrevDiag);
3879 Diag(New->
getLocation(), diag::err_different_language_linkage) << New;
3880 Diag(OldLocation, PrevDiag);
3891 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3896 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3909 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3910 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3913 assert(!OldProto->hasExceptionSpec() &&
"Exception spec in C");
3917 OldProto->getExtProtoInfo());
3923 for (
const auto &ParamType : OldProto->param_types()) {
3930 Params.push_back(Param);
3933 New->setParams(Params);
3936 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3968 NewProto->getReturnType());
3969 bool LooseCompatible = !MergedReturn.
isNull();
3971 LooseCompatible && Idx !=
End; ++Idx) {
3975 NewProto->getParamType(Idx))) {
3976 ArgTypes.push_back(NewParm->
getType());
3980 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3981 NewProto->getParamType(Idx) };
3982 Warnings.push_back(Warn);
3983 ArgTypes.push_back(NewParm->
getType());
3985 LooseCompatible =
false;
3988 if (LooseCompatible) {
3989 for (
unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3990 Diag(Warnings[Warn].NewParm->getLocation(),
3991 diag::ext_param_promoted_not_compatible_with_prototype)
3992 << Warnings[Warn].PromotedType
3993 << Warnings[Warn].OldParm->getType();
3994 if (Warnings[Warn].OldParm->getLocation().isValid())
3995 Diag(Warnings[Warn].OldParm->getLocation(),
3996 diag::note_previous_declaration);
3999 if (MergeTypeWithOld)
4002 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4019 Diag(OldLocation, diag::note_previous_builtin_declaration)
4024 PrevDiag = diag::note_previous_builtin_declaration;
4028 Diag(OldLocation, PrevDiag) << Old << Old->
getType();
4042 Scope *S,
bool MergeTypeWithOld) {
4044 mergeDeclAttributes(New, Old);
4057 for (
unsigned i = 0, e = New->
getNumParams(); i != e; ++i) {
4065 return MergeCXXFunctionDecl(New, Old, S);
4071 if (!Merged.isNull() && MergeTypeWithOld)
4082 ? (oldMethod->
isOptional() ? AMK_OptionalProtocolImplementation
4083 : AMK_ProtocolImplementation)
4084 : isa<ObjCImplDecl>(newMethod->
getDeclContext()) ? AMK_Redeclaration
4087 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4094 ni != ne && oi != oe; ++ni, ++oi)
4097 CheckObjCMethodOverride(newMethod, oldMethod);
4104 ? diag::err_redefinition_different_type
4105 : diag::err_redeclaration_different_type)
4110 std::tie(PrevDiag, OldLocation)
4112 S.
Diag(OldLocation, PrevDiag);
4124 bool MergeTypeWithOld) {
4135 return MergeVarDeclExceptionSpecs(New, Old);
4152 QualType PrevVDTy = PrevVD->getType();
4206 if (MergeTypeWithOld)
4252 if (!shouldLinkPossiblyHiddenDecl(
Previous, New))
4262 OldTemplate = dyn_cast<VarTemplateDecl>(
Previous.getFoundDecl());
4266 dyn_cast<UsingShadowDecl>(
Previous.getRepresentativeDecl()))
4267 if (checkUsingShadowRedecl<VarTemplateDecl>(*
this, Shadow, NewTemplate))
4270 Old = dyn_cast<VarDecl>(
Previous.getFoundDecl());
4273 dyn_cast<UsingShadowDecl>(
Previous.getRepresentativeDecl()))
4274 if (checkUsingShadowRedecl<VarDecl>(*
this, Shadow, New))
4281 notePreviousDefinition(
Previous.getRepresentativeDecl(),
4294 true, TPL_TemplateMatch))
4308 mergeDeclAttributes(New, Old);
4311 if (New->
hasAttr<WeakImportAttr>() &&
4313 !Old->
hasAttr<WeakImportAttr>()) {
4320 if (
const auto *ILA = New->
getAttr<InternalLinkageAttr>())
4321 if (!Old->
hasAttr<InternalLinkageAttr>()) {
4325 New->
dropAttr<InternalLinkageAttr>();
4330 if (MostRecent != Old) {
4331 MergeVarDeclTypes(New, MostRecent,
4343 std::tie(PrevDiag, OldLocation) =
4350 if (getLangOpts().MicrosoftExt) {
4353 Diag(OldLocation, PrevDiag);
4357 Diag(OldLocation, PrevDiag);
4376 Diag(OldLocation, PrevDiag);
4384 Diag(OldLocation, PrevDiag);
4390 Diag(OldLocation, PrevDiag);
4394 if (CheckRedeclarationInModule(New, Old))
4406 Diag(OldLocation, PrevDiag);
4416 Diag(Def->getLocation(), diag::note_previous_definition);
4430 Diag(OldLocation, PrevDiag);
4433 Diag(OldLocation, PrevDiag);
4441 Diag(OldLocation, PrevDiag);
4452 diag::warn_deprecated_redundant_constexpr_static_def);
4454 if (checkVarDeclRedefinition(Def, New))
4460 Diag(New->
getLocation(), diag::err_different_language_linkage) << New;
4461 Diag(OldLocation, PrevDiag);
4490 auto &HSI = PP.getHeaderSearchInfo();
4491 StringRef HdrFilename =
4494 auto noteFromModuleOrInclude = [&](
Module *Mod,
4500 if (IncLoc.isValid()) {
4502 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4508 Diag(IncLoc, diag::note_redefinition_include_same_file)
4509 << HdrFilename.str();
4519 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4524 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4527 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4542 if (!hasVisibleDefinition(Old) &&
4554 makeMergedDefinitionVisible(OldTD);
4555 makeMergedDefinitionVisible(Old);
4582 ? S->getMSCurManglingNumber()
4583 : S->getMSLastManglingNumber();
4590 if (isa<CXXRecordDecl>(Tag->
getParent())) {
4605 Decl *ManglingContextDecl;
4606 std::tie(MCtx, ManglingContextDecl) =
4616 struct NonCLikeKind {
4628 explicit operator bool() {
return Kind != None; }
4636 return {NonCLikeKind::Invalid, {}};
4643 return {NonCLikeKind::BaseClass,
4646 bool Invalid =
false;
4655 if (
auto *FD = dyn_cast<FieldDecl>(D)) {
4656 if (FD->hasInClassInitializer()) {
4657 auto *Init = FD->getInClassInitializer();
4658 return {NonCLikeKind::DefaultMemberInit,
4666 if (isa<FriendDecl>(D))
4671 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4674 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4682 if (MemberRD->isLambda())
4683 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4687 if (MemberRD->isThisDeclarationADefinition()) {
4723 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4727 if (NonCLike || ChangesLinkage) {
4728 if (NonCLike.Kind == NonCLikeKind::Invalid)
4731 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4732 if (ChangesLinkage) {
4735 DiagID = diag::err_typedef_changes_linkage;
4737 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4743 TextToInsert +=
' ';
4746 Diag(FixitLoc, DiagID)
4747 << isa<TypeAliasDecl>(NewTD)
4750 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4751 << NonCLike.Kind - 1 << NonCLike.Range;
4754 << NewTD << isa<TypeAliasDecl>(NewTD);
4777 llvm_unreachable(
"unexpected type specifier");
4787 bool IsExplicitInstantiation,
4789 Decl *TagD =
nullptr;
4804 if (isa<TagDecl>(TagD))
4805 Tag = cast<TagDecl>(TagD);
4807 Tag = CTD->getTemplatedDecl();
4811 handleTagNumbering(Tag, S);
4822 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4828 << getLangOpts().CPlusPlus17;
4846 DiagnoseFunctionSpecifiers(DS);
4853 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4857 bool IsExplicitSpecialization =
4858 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4860 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4861 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4870 Diag(SS.
getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4876 bool DeclaresAnything =
true;
4879 if (
RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4880 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4883 Record->getDeclContext()->isRecord()) {
4891 if (CurContext->isFunctionOrMethod())
4892 AnonRecord = Record;
4893 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4897 DeclaresAnything =
false;
4907 if (!getLangOpts().
CPlusPlus && CurContext->isRecord() &&
4920 Record = dyn_cast<RecordDecl>(Tag);
4923 Record = RT->getDecl();
4925 Record = UT->getDecl();
4927 if (Record && getLangOpts().MicrosoftExt) {
4930 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4933 DeclaresAnything =
false;
4944 if (
EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4945 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4946 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4947 DeclaresAnything =
false;
4955 DeclaresAnything =
false;
4964 ActOnDocumentableDecl(TagD);
4974 if (!DeclaresAnything) {
4977 Diag(DS.
getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4978 ? diag::err_no_declarators
4979 : diag::ext_no_declarators)
4992 unsigned DiagID = diag::warn_standalone_specifier;
4994 DiagID = diag::ext_standalone_specifier;
5035 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5059 assert(PrevDecl &&
"Expected a non-null Decl");
5064 SemaRef.
Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5066 SemaRef.
Diag(PrevDecl->
getLocation(), diag::note_previous_declaration);
5091 bool Invalid =
false;
5094 for (
auto *D : AnonRecord->
decls()) {
5095 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5096 cast<NamedDecl>(D)->getDeclName()) {
5112 unsigned OldChainingSize = Chaining.size();
5114 Chaining.append(IF->chain_begin(), IF->chain_end());
5116 Chaining.push_back(VD);
5118 assert(Chaining.size() >= 2);
5121 for (
unsigned i = 0; i < Chaining.size(); i++)
5122 NamedChain[i] = Chaining[i];
5126 VD->
getType(), {NamedChain, Chaining.size()});
5138 Chaining.resize(OldChainingSize);
5153 "Parser allowed 'typedef' as storage class VarDecl.");
5154 switch (StorageClassSpec) {
5168 llvm_unreachable(
"unknown storage class specifier");
5174 for (
const auto *I : Record->
decls()) {
5175 const auto *FD = dyn_cast<FieldDecl>(I);
5176 if (
const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5177 FD = IFD->getAnonField();
5178 if (FD && FD->hasInClassInitializer())
5179 return FD->getLocation();
5182 llvm_unreachable(
"couldn't find in-class initializer");
5187 if (!
Parent->isUnion() || !
Parent->hasInClassInitializer())
5190 S.
Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5196 if (!
Parent->isUnion() || !
Parent->hasInClassInitializer())
5217 else if (!Record->
isUnion() && !getLangOpts().
C11)
5222 bool Invalid =
false;
5224 const char *PrevSpec =
nullptr;
5235 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5241 PrevSpec, DiagID, Policy);
5247 isa<RecordDecl>(Owner)) {
5249 diag::err_anonymous_union_with_storage_spec)
5263 << Record->
isUnion() <<
"const"
5267 diag::ext_anonymous_struct_union_qualified)
5268 << Record->
isUnion() <<
"volatile"
5272 diag::ext_anonymous_struct_union_qualified)
5273 << Record->
isUnion() <<
"restrict"
5277 diag::ext_anonymous_struct_union_qualified)
5278 << Record->
isUnion() <<
"_Atomic"
5282 diag::ext_anonymous_struct_union_qualified)
5283 << Record->
isUnion() <<
"__unaligned"
5293 for (
auto *Mem : Record->
decls()) {
5295 if (Mem->isInvalidDecl())
5298 if (
auto *FD = dyn_cast<FieldDecl>(Mem)) {
5302 assert(FD->getAccess() !=
AS_none);
5304 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5314 if (CheckNontrivialField(FD))
5316 }
else if (Mem->isImplicit()) {
5318 }
else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5323 }
else if (
auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5324 if (!MemRecord->isAnonymousStructOrUnion() &&
5325 MemRecord->getDeclName()) {
5327 if (getLangOpts().MicrosoftExt)
5328 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5332 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5340 Diag(MemRecord->getLocation(),
5341 diag::ext_anonymous_record_with_anonymous_type)
5344 }
else if (isa<AccessSpecDecl>(Mem)) {
5346 }
else if (isa<StaticAssertDecl>(Mem)) {
5351 unsigned DK = diag::err_anonymous_record_bad_member;
5352 if (isa<TypeDecl>(Mem))
5353 DK = diag::err_anonymous_record_with_type;
5354 else if (isa<FunctionDecl>(Mem))
5355 DK = diag::err_anonymous_record_with_function;
5356 else if (isa<VarDecl>(Mem))
5357 DK = diag::err_anonymous_record_with_static;
5360 if (getLangOpts().MicrosoftExt &&
5361 DK == diag::err_anonymous_record_with_type)
5362 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5365 Diag(Mem->getLocation(), DK) << Record->
isUnion();
5374 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5377 cast<CXXRecordDecl>(Record));
5382 << getLangOpts().CPlusPlus;
5401 assert(TInfo &&
"couldn't build declarator info for anonymous struct/union");
5405 if (
RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5412 ProcessDeclAttributes(S, Anon, Dc);
5415 FieldCollector->Add(cast<FieldDecl>(Anon));
5436 ActOnUninitializedDecl(Anon);
5452 Chain.push_back(Anon);
5457 if (
VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5458 if (getLangOpts().
CPlusPlus && NewVD->isStaticLocal()) {
5460 Decl *ManglingContextDecl;
5461 std::tie(MCtx, ManglingContextDecl) =
5462 getCurrentMangleNumberContext(NewVD->getDeclContext());
5493 assert(Record &&
"expected a record!");
5498 assert(TInfo &&
"couldn't build declarator info for anonymous struct");
5500 auto *ParentDecl = cast<RecordDecl>(CurContext);
5506 nullptr, RecTy, TInfo,
5512 CurContext->addDecl(Anon);
5518 Chain.push_back(Anon);
5521 if (RequireCompleteSizedType(Anon->
getLocation(), RecTy,
5522 diag::err_field_incomplete_or_sizeless) ||
5526 ParentDecl->setInvalidDecl();
5535 return GetNameFromUnqualifiedId(D.
getName());
5542 NameInfo.
setLoc(Name.StartLocation);
5544 switch (Name.getKind()) {
5548 NameInfo.
setName(Name.Identifier);
5564 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5565 Diag(Name.StartLocation,
5566 diag::err_deduction_guide_name_not_class_template)
5567 << (
int)getTemplateNameKindForDiagnostics(TN) << TN;
5569 Diag(Template->getLocation(), diag::note_template_decl_here);
5580 Name.OperatorFunctionId.Operator));
5582 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5593 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5604 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5617 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5618 if (!CurClass || CurClass->
getIdentifier() != Name.TemplateId->Name)
5637 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5654 llvm_unreachable(
"Unknown name kind");
5680 if (Declaration->param_size() != Definition->param_size())
5682 for (
unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5683 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5684 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5696 (DeclTyName && DeclTyName == DefTyName))
5697 Params.push_back(Idx);
5738 if (!TSI)
return true;
5750 if (Result.isInvalid())
return true;
5795 << D << static_cast<int>(Status);
5803 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5823 Record = dyn_cast<CXXRecordDecl>(Record->
getParent());
5825 Diag(NameInfo.
getLoc(), diag::err_member_name_of_class) << Name;
5852 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5866 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5867 : diag::err_member_extra_qualification)
5871 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5879 if (!Cur->
Encloses(DC) && !IsTemplateId) {
5881 Diag(Loc, diag::err_member_qualification)
5883 else if (isa<TranslationUnitDecl>(DC))
5884 Diag(Loc, diag::err_invalid_declarator_global_scope)
5886 else if (isa<FunctionDecl>(Cur))
5887 Diag(Loc, diag::err_invalid_declarator_in_function)
5889 else if (isa<BlockDecl>(Cur))
5890 Diag(Loc, diag::err_invalid_declarator_in_block)
5892 else if (isa<ExportDecl>(Cur)) {
5893 if (!isa<NamespaceDecl>(DC))
5894 Diag(Loc, diag::err_export_non_namespace_scope_name)
5901 Diag(Loc, diag::err_invalid_declarator_scope)
5902 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.
getRange();
5909 Diag(Loc, diag::err_member_qualification)
5931 if (isa_and_nonnull<DecltypeType>(
5933 Diag(Loc, diag::err_decltype_in_declarator)
5948 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5954 }
else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5968 UPPC_DeclarationQualifier))
5973 if (!DC || isa<EnumDecl>(DC)) {
5979 diag::err_template_qualified_declarator_no_match)
5986 if (!IsDependentContext &&
5991 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->
hasDefinition()) {
5993 diag::err_member_def_undefined_record)
5998 if (diagnoseQualifiedDeclaration(
6010 if (EnteringContext && IsDependentContext &&
6011 TemplateParamLists.size() != 0) {
6022 UPPC_DeclarationType))
6026 forRedeclarationInCurContext());
6030 bool IsLinkageLookup =
false;
6031 bool CreateBuiltins =
false;
6042 else if (CurContext->isFunctionOrMethod() &&
6045 IsLinkageLookup =
true;
6047 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6048 }
else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6050 CreateBuiltins =
true;
6052 if (IsLinkageLookup) {
6053 Previous.clear(LookupRedeclarationWithLinkage);
6054 Previous.setRedeclarationKind(ForExternalRedeclaration);
6057 LookupName(
Previous, S, CreateBuiltins);
6091 Previous.getFoundDecl()->isTemplateParameter()) {
6101 if (!R->
isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6117 CheckExtraCXXDefaultArguments(D);
6121 bool AddToScope =
true;
6123 if (TemplateParamLists.size()) {
6128 New = ActOnTypedefDeclarator(S, D, DC, TInfo,
Previous);
6130 New = ActOnFunctionDeclarator(S, D, DC, TInfo,
Previous,
6134 New = ActOnVariableDeclarator(S, D, DC, TInfo,
Previous, TemplateParamLists,
6144 PushOnScopeChains(New, S);
6146 if (isInOpenMPDeclareTargetContext())
6147 checkDeclIsAllowedInOpenMPTarget(
nullptr, New);
6157 bool &SizeIsNegative,
6163 SizeIsNegative =
false;
6172 if (
const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6177 if (FixedType.
isNull())
return FixedType;
6179 return Qs.
apply(Context, FixedType);
6181 if (
const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6182 QualType Inner = PTy->getInnerType();
6186 if (FixedType.
isNull())
return FixedType;
6188 return Qs.
apply(Context, FixedType);
6198 SizeIsNegative, Oversized);
6211 if (Res.isSigned() && Res.isNegative()) {
6212 SizeIsNegative =
true;
6217 unsigned ActiveSizeBits =
6221 : Res.getActiveBits();
6229 return Qs.
apply(Context, FoldedArrayType);
6254 TypeLoc DstElemTL = DstATL.getElementLoc();
6273 bool &SizeIsNegative,
6277 SizeIsNegative, Oversized);
6290 unsigned FailedFoldDiagID) {
6291 bool SizeIsNegative;
6294 TInfo, Context, SizeIsNegative, Oversized);
6296 Diag(Loc, diag::ext_vla_folded_to_constant);
6303 Diag(Loc, diag::err_typecheck_negative_array_size);
6304 else if (Oversized.getBoolValue())
6305 Diag(Loc, diag::err_array_too_large) <<
toString(Oversized, 10);
6306 else if (FailedFoldDiagID)
6307 Diag(Loc, FailedFoldDiagID);
6329 return Result.empty() ? nullptr : *Result.begin();
6339 diag::err_virtual_non_function);
6343 diag::err_explicit_non_function);
6347 diag::err_noreturn_non_function);
6367 << getLangOpts().CPlusPlus17;
6375 diag::err_deduction_guide_invalid_specifier)
6384 if (!NewTD)
return nullptr;
6387 ProcessDeclAttributes(S, NewTD, D);
6389 CheckTypedefForVariablyModifiedType(S, NewTD);
6406 setFunctionHasBranchProtectedScope();
6408 if (S->getFnParent() ==
nullptr) {
6409 bool SizeIsNegative;
6423 else if (Oversized.getBoolValue())
6446 FilterLookupForScope(
Previous, DC, S,
false,
6450 Redeclaration =
true;
6451 MergeTypedefNameDecl(S, NewTD,
Previous);
6453 inferGslPointerAttribute(NewTD);
6456 if (ShadowedDecl && !Redeclaration)
6457 CheckShadow(NewTD, ShadowedDecl,
Previous);
6463 if (II->isStr(
"FILE"))
6465 else if (II->isStr(
"jmp_buf"))
6467 else if (II->isStr(
"sigjmp_buf"))
6469 else if (II->isStr(
"ucontext_t"))
6527 if (!OuterContext->
Equals(PrevOuterContext))
6536 if (!SS.
isSet())
return;
6545 unsigned kind = -1
U;
6547 if (
var->hasAttr<BlocksAttr>())
6549 else if (!
var->hasLocalStorage())
6551 }
else if (isa<ObjCIvarDecl>(
decl)) {
6553 }
else if (isa<FieldDecl>(
decl)) {
6558 Diag(
decl->getLocation(), diag::err_arc_autoreleasing_var)
6563 if (!
type->isObjCLifetimeType())
6566 lifetime =
type->getObjCARCImplicitLifetime();
6574 var->getTLSKind()) {
6575 Diag(
var->getLocation(), diag::err_arc_thread_ownership)
6585 if (
Decl->getType().hasAddressSpace())
6587 if (
Decl->getType()->isDependentType())
6598 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6599 Var->hasGlobalStorage())
6603 if (
auto DT = dyn_cast<DecayedType>(
Type)) {
6604 auto OrigTy = DT->getOriginalType();
6605 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6637 if (WeakRefAttr *
Attr = ND.
getAttr<WeakRefAttr>()) {
6645 if (
auto *VD = dyn_cast<VarDecl>(&ND)) {
6646 if (VD->hasInit()) {
6647 if (
const auto *
Attr = VD->getAttr<AliasAttr>()) {
6648 assert(VD->isThisDeclarationADefinition() &&
6649 !VD->isExternallyVisible() &&
"Broken AliasAttr handled late!");
6651 VD->dropAttr<AliasAttr>();
6658 if (SelectAnyAttr *
Attr = ND.
getAttr<SelectAnyAttr>()) {
6661 diag::err_attribute_selectany_non_extern_data);
6667 auto *VD = dyn_cast<VarDecl>(&ND);
6668 bool IsAnonymousNS =
false;
6671 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6672 while (NS && !IsAnonymousNS) {
6674 NS = dyn_cast<NamespaceDecl>(NS->
getParent());
6681 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6683 (!AnonNSInMicrosoftMode &&
6692 if (
const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6697 for (
TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6703 if (
const auto *A = ATL.
getAttrAs<LifetimeBoundAttr>()) {
6704 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6705 if (!MD || MD->isStatic()) {
6706 S.
Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6707 << !MD << A->getRange();
6708 }
else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6709 S.
Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6710 << isa<CXXDestructorDecl>(MD) << A->getRange();
6719 bool IsSpecialization,
6720 bool IsDefinition) {
6724 bool IsTemplate =
false;
6725 if (
TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6726 OldDecl = OldTD->getTemplatedDecl();
6728 if (!IsSpecialization)
6729 IsDefinition =
false;
6731 if (
TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6732 NewDecl = NewTD->getTemplatedDecl();
6736 if (!OldDecl || !NewDecl)
6739 const DLLImportAttr *OldImportAttr = OldDecl->
getAttr<DLLImportAttr>();
6740 const DLLExportAttr *OldExportAttr = OldDecl->
getAttr<DLLExportAttr>();
6741 const DLLImportAttr *NewImportAttr = NewDecl->
getAttr<DLLImportAttr>();
6742 const DLLExportAttr *NewExportAttr = NewDecl->
getAttr<DLLExportAttr>();
6746 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6747 (NewExportAttr && !NewExportAttr->isInherited());
6753 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6755 if (AddsAttr && !IsSpecialization && !OldDecl->
isImplicit()) {
6757 bool JustWarn =
false;
6759 auto *VD = dyn_cast<VarDecl>(OldDecl);
6760 if (VD && !VD->getDescribedVarTemplate())
6762 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6771 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6774 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6775 : diag::err_attribute_dll_redeclaration;
6778 << (NewImportAttr ? (
const Attr *)NewImportAttr : NewExportAttr);
6791 bool IsInline =
false, IsStaticDataMember =
false, IsQualifiedFriend =
false;
6793 if (
const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6796 IsStaticDataMember = VD->isStaticDataMember();
6797 IsDefinition = VD->isThisDeclarationADefinition(S.
Context) !=
6799 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6800 IsInline = FD->isInlined();
6801 IsQualifiedFriend = FD->getQualifier() &&
6805 if (OldImportAttr && !HasNewAttr &&
6806 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6808 if (IsMicrosoftABI && IsDefinition) {
6810 diag::warn_redeclaration_without_import_attribute)
6813 NewDecl->
dropAttr<DLLImportAttr>();
6815 DLLExportAttr::CreateImplicit(S.
Context, NewImportAttr->getRange()));
6818 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6819 << NewDecl << OldImportAttr;
6821 S.
Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6822 OldDecl->
dropAttr<DLLImportAttr>();
6823 NewDecl->
dropAttr<DLLImportAttr>();
6825 }
else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6828 OldDecl->
dropAttr<DLLImportAttr>();
6829 NewDecl->
dropAttr<DLLImportAttr>();
6831 diag::warn_dllimport_dropped_from_inline_function)
6832 << NewDecl << OldImportAttr;
6839 if (
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6841 !NewImportAttr && !NewExportAttr) {
6842 if (
const DLLExportAttr *ParentExportAttr =
6843 MD->getParent()->getAttr<DLLExportAttr>()) {
6844 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.
Context);
6845 NewAttr->setInherited(
true);
6885 template<
typename T>
6889 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6893 if (S.
getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6894 D->template hasAttr<CUDAHostAttr>()))
6897 return D->isExternC();
6903 isa<OMPDeclareMapperDecl>(DC))
6909 if (isa<RequiresExprBodyDecl>(DC))
6911 llvm_unreachable(
"Unexpected context");
6917 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6921 llvm_unreachable(
"Unexpected context");
6967 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
6968 return FD->isExternC();
6969 if (
const auto *VD = dyn_cast<VarDecl>(D))
6970 return VD->isExternC();
6972 llvm_unreachable(
"Unknown type of decl!");
6985 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6999 diag::err_invalid_type_for_program_scope_var)
7028 Se.
Diag(NewVD->
getLocation(), diag::err_opencl_half_declaration) << R;
7061 Se.
Diag(NewVD->
getLocation(), diag::err_opencl_nonconst_global_sampler);
7071 template <
typename AttrTy>
7074 if (
const auto *Attribute = TND->
getAttr<AttrTy>()) {
7075 AttrTy *Clone = Attribute->clone(S.
Context);
7076 Clone->setInherited(
true);
7094 if (!Decomp.bindings().empty()) {
7095 II = Decomp.bindings()[0].Name;
7114 bool IsLocalExternDecl = SC ==
SC_Extern &&
7115 adjustContextForLocalExternDecl(DC);
7126 !D.
getAsmLabel() && !getSourceManager().isInSystemMacro(
7132 getLangOpts().
CPlusPlus17 ? diag::ext_register_storage_class
7133 : diag::warn_deprecated_register)
7139 if (!DC->
isRecord() && S->getFnParent() ==
nullptr) {
7155 bool IsMemberSpecialization =
false;
7156 bool IsVariableTemplateSpecialization =
false;
7158 bool IsVariableTemplate =
false;
7167 ParsingInitForAutoVars.insert(NewVD);
7175 NTCUC_AutoVar, NTCUK_Destruct);
7177 bool Invalid =
false;
7179 if (DC->
isRecord() && !CurContext->isRecord()) {
7186 diag::err_static_out_of_line)
7198 diag::err_storage_class_for_static_member)
7202 llvm_unreachable(
"C storage class in c++!");
7206 if (SC ==
SC_Static && CurContext->isRecord()) {
7207 if (
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7213 if (Ctxt->isFunctionOrMethod()) {
7214 FunctionOrMethod = Ctxt;
7217 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7219 AnonStruct = ParentDecl;
7223 if (FunctionOrMethod) {
7227 diag::err_static_data_member_not_allowed_in_local_class)
7228 << Name << RD->getDeclName() << RD->getTagKind();
7229 }
else if (AnonStruct) {
7234 diag::err_static_data_member_not_allowed_in_anon_struct)
7237 }
else if (RD->isUnion()) {
7242 ? diag::warn_cxx98_compat_static_data_member_in_union
7243 : diag::ext_static_data_member_in_union) << Name;
7250 bool InvalidScope =
false;
7251 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7258 false, IsMemberSpecialization, InvalidScope);
7259 Invalid |= InvalidScope;
7261 if (TemplateParams) {
7262 if (!TemplateParams->
size() &&
7267 diag::err_template_variable_noparams)
7271 TemplateParams =
nullptr;
7274 if (CheckTemplateDeclScope(S, TemplateParams))
7279 IsVariableTemplateSpecialization =
true;
7283 IsVariableTemplate =
true;
7288 ? diag::warn_cxx11_compat_variable_template
7289 : diag::ext_variable_template);
7294 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7295 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7299 "should have a 'template<>' for this decl");
7302 if (IsVariableTemplateSpecialization) {
7304 TemplateParamLists.size() > 0
7305 ? TemplateParamLists[0]->getTemplateLoc()
7307 DeclResult Res = ActOnVarTemplateSpecialization(
7308 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7312 NewVD = cast<VarDecl>(Res.
get());
7323 if (IsVariableTemplate) {
7326 TemplateParams, NewVD);
7333 ParsingInitForAutoVars.insert(NewVD);
7345 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7346 if (TemplateParamLists.size() > VDTemplateParamLists)
7348 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7355 }
else if (CurContext->isFunctionOrMethod()) {
7358 diag::err_inline_declaration_block_scope) << Name
7362 getLangOpts().
CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7363 : diag::ext_inline_variable);
7374 if (IsLocalExternDecl) {
7377 B->setLocalExternDecl();
7382 bool EmitTLSUnsupportedError =
false;
7395 diag::err_thread_non_global)
7398 if (getLangOpts().
CUDA || getLangOpts().OpenMPIsDevice ||
7399 getLangOpts().SYCLIsDevice) {
7403 EmitTLSUnsupportedError =
true;
7410 diag::err_thread_unsupported);
7417 if (getLangOpts().SYCLIsDevice) {
7419 isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
7427 !isTypeDecoratedWithDeclAttribute<SYCLGlobalVariableAllowedAttr>(
7439 diag::err_constexpr_wrong_decl_kind)
7449 (getLangOpts().CPlusPlus17 ||
7457 diag::err_constinit_local_variable);
7459 NewVD->
addAttr(ConstInitAttr::Create(
7474 if (SC ==
SC_Static && S->getFnParent() !=
nullptr &&
7479 diag::warn_static_local_in_extern_inline);
7480 MaybeSuggestAddingStaticToDecl(CurFD);
7485 if (IsVariableTemplateSpecialization)
7490 else if (IsMemberSpecialization)
7505 B->setModulePrivate();
7509 if (getLangOpts().
OpenCL) {
7510 deduceOpenCLAddressSpace(NewVD);
7515 diag::err_opencl_unknown_type_specifier)
7516 << getLangOpts().getOpenCLVersionString()
7523 ProcessDeclAttributes(S, NewVD, D);
7531 copyAttrFromTypedefToDecl<AllocSizeAttr>(*
this, NewVD, TT);
7533 if (getLangOpts().
CUDA || getLangOpts().OpenMPIsDevice ||
7534 getLangOpts().SYCLIsDevice) {
7535 if (EmitTLSUnsupportedError &&
7537 (getLangOpts().OpenMPIsDevice &&
7538 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7540 diag::err_thread_unsupported);
7542 if (EmitTLSUnsupportedError &&
7543 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7547 if (SC ==
SC_None && S->getFnParent() !=
nullptr &&
7548 (NewVD->
hasAttr<CUDASharedAttr>() ||
7549 NewVD->
hasAttr<CUDAConstantAttr>())) {
7557 assert(!NewVD->
hasAttr<DLLImportAttr>() ||
7558 NewVD->
getAttr<DLLImportAttr>()->isInherited() ||
7563 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7571 if (S->getFnParent() !=
nullptr) {
7575 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) <<
Label;
7581 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) <<
Label;
7592 bool HasSizeMismatch;
7594 if (!TI.isValidGCCRegisterName(
Label))
7595 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) <<
Label;
7596 else if (!TI.validateGlobalRegisterVariable(
Label,
7599 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) <<
Label;
7600 else if (HasSizeMismatch)
7601 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) <<
Label;
7613 }
else if (!ExtnameUndeclaredIdentifiers.empty()) {
7614 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7616 if (I != ExtnameUndeclaredIdentifiers.end()) {
7619 ExtnameUndeclaredIdentifiers.erase(I);
7628 ? getShadowedDeclaration(NewVD,
Previous)
7636 IsMemberSpecialization ||
7637 IsVariableTemplateSpecialization);
7645 isDeclInScope(
Previous.getFoundDecl(), OriginalDC, S,
false));
7652 CheckMemberSpecialization(NewVD,
Previous))
7658 isa<FieldDecl>(
Previous.getFoundDecl()) &&
7675 if (!IsVariableTemplateSpecialization)
7687 if (CheckTemplateParameterList(
7693 ? TPC_ClassTemplateMember
7699 if (PrevVarTemplate &&
7707 CheckShadow(NewVD, ShadowedDecl,
Previous);
7709 ProcessPragmaWeak(S, NewVD);
7715 RegisterLocallyScopedExternCDecl(NewVD, S);
7719 Decl *ManglingContextDecl;
7720 std::tie(MCtx, ManglingContextDecl) =
7731 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr(
"main") &&
7755 ActOnDocumentableDecl(NewTemplate);
7760 CompleteMemberSpecialization(NewVD,
Previous);
7762 addSyclVarDecl(NewVD);
7780 if (isa<TypeAliasDecl>(ShadowedDecl))
7782 else if (isa<TypedefDecl>(ShadowedDecl))
7784 else if (isa<BindingDecl>(ShadowedDecl))
7786 else if (isa<RecordDecl>(OldDC))
7825 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7841 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl :
nullptr;
7852 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7869 if (
FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7877 if (isa<CXXConstructorDecl>(NewDC))
7878 if (
const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7881 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7886 if (
VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7887 if (shadowedVar->isExternC()) {
7890 for (
auto I : shadowedVar->redecls())
7891 if (I->isFileVarDecl()) {
7899 unsigned WarningDiag = diag::warn_decl_shadow;
7901 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7902 isa<CXXMethodDecl>(NewDC)) {
7903 if (
const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->
getParent())) {
7905 if (RD->getLambdaCaptureDefault() ==
LCD_None) {
7907 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7911 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7915 cast<LambdaScopeInfo>(getCurFunction())
7916 ->ShadowingDecls.push_back(
7917 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7922 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7926 ParentDC && !ParentDC->
Equals(OldDC);
7930 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7960 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7969 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7974 ? diag::warn_decl_shadow_uncaptured_local
7975 : diag::warn_decl_shadow)
7976 << Shadow.VD->getDeclName()
7979 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7980 << Shadow.VD->getDeclName() << 0;
7987 if (Diags.isIgnored(diag::warn_decl_shadow, D->
getLocation()))
7993 if (
NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7994 CheckShadow(D, ShadowedDecl, R);
8001 if (!getLangOpts().
CPlusPlus || ShadowingDecls.empty())
8004 auto *DRE = dyn_cast<DeclRefExpr>(E);
8007 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8008 auto I = ShadowingDecls.find(D);
8009 if (I == ShadowingDecls.end())
8011 const NamedDecl *ShadowedDecl = I->second;
8013 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8018 ShadowingDecls.erase(I);
8023 template<
typename T>
8026 assert(S.
getLangOpts().CPlusPlus &&
"only C++ has extern \"C\"");
8047 if (!isa<VarDecl>(ND))
8057 if (isa<VarDecl>(*I)) {
8067 if (isa<VarDecl>(*I)) {
8085 assert(Prev &&
"should have found a previous declaration to diagnose");
8087 Prev = FD->getFirstDecl();
8089 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8091 S.
Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8106 template<
typename T>
8113 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8125 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8150 CheckAlignasUnderalignment(NewVD);
8172 if (getLangOpts().OpenCLVersion == 120 &&
8173 !getOpenCLOptions().isAvailableOption(
"cl_clang_storage_class_specifiers",
8181 if (getLangOpts().
OpenCL) {
8186 if (NewVD->
hasAttr<BlocksAttr>()) {
8195 Diag(NewVD->
getLocation(), diag::err_opencl_invalid_block_declaration)
8201 Diag(NewVD->
getLocation(), diag::err_opencl_extern_block_declaration);
8213 getOpenCLOptions().areProgramScopeVariablesSupported(
8216 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8217 Diag(NewVD->
getLocation(), diag::err_opencl_global_invalid_addr_space)
8218 <<
Scope <<
"global or constant";
8220 Diag(NewVD->
getLocation(), diag::err_opencl_global_invalid_addr_space)
8221 <<
Scope <<
"constant";
8237 if (FD && !FD->
hasAttr<OpenCLKernelAttr>()) {
8249 if (FD && FD->
hasAttr<OpenCLKernelAttr>()) {
8250 if (!getCurScope()->isFunctionScope()) {
8274 && !NewVD->
hasAttr<BlocksAttr>()) {
8278 assert(!getLangOpts().ObjCAutoRefCount);
8284 if (isVM || NewVD->
hasAttr<CleanupAttr>() ||
8286 setFunctionHasBranchProtectedScope();
8290 bool SizeIsNegative;
8296 FixedT = FixedTInfo->
getType();
8297 else if (FixedTInfo) {
8359 if (isVM && NewVD->
hasAttr<BlocksAttr>()) {
8367 diag::err_constexpr_var_non_literal)) {
8394 CheckVariableDeclarationType(NewVD);
8434 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8436 IsOverload(MD, BaseMD,
false,
8443 if (Overridden.insert(BaseMD).second) {
8445 CheckOverridingFunctionReturnType(MD, BaseMD);
8446 CheckOverridingFunctionAttributes(MD, BaseMD);
8447 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8448 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8460 return !Overridden.empty();
8466 struct ActOnFDArgs {
8482 : Context(Context), OriginalFD(TypoFD),
8485 bool ValidateCandidate(
const TypoCorrection &candidate)
override {
8491 CDeclEnd = candidate.
end();
8492 CDecl != CDeclEnd; ++CDecl) {
8499 if (
Parent &&
Parent->getCanonicalDecl() == ExpectedParent)
8501 }
else if (!ExpectedParent) {
8510 std::unique_ptr<CorrectionCandidateCallback> clone()
override {
8511 return std::make_unique<DifferentNameValidatorCCC>(*
this);
8523 TypoCorrectedFunctionDefinitions.insert(F);
8537 ActOnFDArgs &ExtraArgs,
bool IsLocalFriend,
Scope *S) {
8543 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8545 IsLocalFriend ? diag::err_no_matching_local_friend :
8547 diag::err_member_decl_does_not_match;
8559 "Cannot have an ambiguity in previous-declaration lookup");
8561 DifferentNameValidatorCCC CCC(SemaRef.
Context, NewFD,
8563 if (!Prev.
empty()) {
8565 Func != FuncEnd; ++Func) {
8572 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8573 NearMatches.push_back(std::make_pair(FD, ParamNum));
8580 IsLocalFriend ?
nullptr : NewDC))) {
8583 ExtraArgs.D.getIdentifierLoc());
8587 CDeclEnd = Correction.
end();
8588 CDecl != CDeclEnd; ++CDecl) {
8595 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8608 ExtraArgs.S, ExtraArgs.D,
8611 ExtraArgs.AddToScope);
8622 if ((*I)->getCanonicalDecl() == Canonical)
8629 SemaRef.
PDiag(IsLocalFriend
8630 ? diag::err_no_matching_local_friend_suggest
8631 : diag::err_member_decl_does_not_match_suggest)
8632 << Name << NewDC << IsDefinition);
8637 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8638 ExtraArgs.D.getIdentifierLoc());
8639 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8645 << Name << NewDC << IsDefinition << NewFD->
getLocation();
8647 bool NewFDisConst =
false;
8649 NewFDisConst = NewMD->isConst();
8652 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8653 NearMatch != NearMatchEnd; ++NearMatch) {
8656 bool FDisConst = MD && MD->
isConst();
8657 bool IsMember = MD || !IsLocalFriend;
8660 if (
unsigned Idx = NearMatch->second) {
8664 SemaRef.
Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8665 : diag::note_local_decl_close_param_match)
8668 }
else if (FDisConst != NewFDisConst) {
8669 SemaRef.
Diag(FD->
getLocation(), diag::note_member_def_close_const_match)
8673 .getConstQualifierLoc())
8676 .getLocWithOffset(1),
8680 IsMember ? diag::note_member_def_close_match
8681 : diag::note_local_decl_close_match);
8688 default: llvm_unreachable(
"Unknown storage class!");
8693 diag::err_typecheck_sclass_func);
8710 diag::err_static_block_func);
8726 bool &IsVirtualOkay) {
8760 diag::err_constexpr_wrong_decl_kind)
8761 <<
static_cast<int>(ConstexprKind);
8779 "Constructors can only be declared in a member context");
8785 isInline,
false, ConstexprKind,
8796 false, ConstexprKind,
8797 TrailingRequiresClause);
8805 IsVirtualOkay =
true;
8817 true, ConstexprKind, TrailingRequiresClause);
8823 diag::err_conv_function_not_member);
8831 IsVirtualOkay =
true;
8836 TrailingRequiresClause);
8839 if (TrailingRequiresClause)
8841 diag::err_trailing_requires_clause_on_deduction_guide)
8853 if (Name.getAsIdentifierInfo() &&
8854 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8866 IsVirtualOkay = !
Ret->isStatic();
8880 true , ConstexprKind, TrailingRequiresClause);
8897 StringRef SizeTypeNames[] = {
"size_t",
"intptr_t",
"uintptr_t",
"ptrdiff_t"};
8905 if (Names.end() != Match)
8910 }
while (DesugaredTy != Ty);
8943 "__cl_clang_non_portable_kernel_param_types", S.
getLangOpts()) &&
8987 "__cl_clang_non_portable_kernel_param_types", S.
getLangOpts()) &&
9001 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9053 S.
Diag(Loc, diag::note_entity_declared_at) << PT;
9076 HistoryStack.push_back(
nullptr);
9085 VisitStack.push_back(RecTy->
getDecl());
9086 assert(VisitStack.back() &&
"First decl null?");
9089 const Decl *Next = VisitStack.pop_back_val();
9091 assert(!HistoryStack.empty());
9093 if (
const FieldDecl *Hist = HistoryStack.pop_back_val())
9094 ValidTypes.insert(Hist->getType().getTypePtr());
9102 if (
const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9103 HistoryStack.push_back(Field);
9105 QualType FieldTy = Field->getType();
9109 "Unexpected type.");
9114 RD = cast<RecordDecl>(Next);
9118 VisitStack.push_back(
nullptr);
9120 for (
const auto *FD : RD->
fields()) {
9131 VisitStack.push_back(FD);
9142 diag::err_record_with_pointers_kernel_param)
9149 S.
Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9150 << OrigRecDecl->getDeclName();
9155 I = HistoryStack.begin() + 1,
9156 E = HistoryStack.end();
9169 }
while (!VisitStack.empty());
9185 while (S->isClassScope() ||
9186 (LangOpts.CPlusPlus &&
9187 S->isFunctionPrototypeScope()) ||
9189 (S->getEntity() && S->getEntity()->isTransparentContext()))
9206 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9208 if (!TemplateParamLists.empty() &&
9209 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9210 TemplateParamLists.back() = Invented;
9212 TemplateParamLists.push_back(Invented);
9222 diag::err_invalid_thread)
9229 bool isFriend =
false;
9231 bool isMemberSpecialization =
false;
9232 bool isFunctionTemplateSpecialization =
false;
9234 bool isDependentClassScopeExplicitSpecialization =
false;
9235 bool HasExplicitTemplateArgs =
false;
9238 bool isVirtualOkay =
false;
9241 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9245 if (!NewFD)
return nullptr;
9247 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9255 if (IsLocalExternDecl)
9275 if (
Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9280 if (isVirtual &&
Parent->isUnion()) {
9285 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9288 if (
auto *Def =
Parent->getDefinition())
9289 Def->setInitMethod(
true);
9294 isMemberSpecialization =
false;
9295 isFunctionTemplateSpecialization =
false;
9301 bool Invalid =
false;
9303 MatchTemplateParametersToScopeSpecifier(
9309 TemplateParamLists, isFriend, isMemberSpecialization,
9311 if (TemplateParams) {
9313 if (CheckTemplateDeclScope(S, TemplateParams))
9316 if (TemplateParams->
size() > 0) {
9330 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9336 Name, TemplateParams,
9342 if (TemplateParamLists.size() > 1) {
9349 isFunctionTemplateSpecialization =
true;
9351 if (TemplateParamLists.size() > 0)
9367 InsertLoc = getLocForEndOfToken(InsertLoc);
9371 << Name << RemoveRange
9379 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9380 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9385 if (TemplateParamLists.size() > 0)
9392 if (FunctionTemplate)
9402 if (!isVirtualOkay) {
9404 diag::err_virtual_non_function);
9405 }
else if (!CurContext->isRecord()) {
9408 diag::err_virtual_out_of_class)
9414 diag::err_virtual_member_function_template)
9428 (isFriend && CurContext->isDependentContext())) &&
9447 if (CurContext->isFunctionOrMethod()) {
9450 diag::err_inline_declaration_block_scope) << Name
9460 !isa<CXXDeductionGuideDecl>(NewFD)) {
9461 if (!CurContext->isRecord()) {
9464 diag::err_explicit_out_of_class)
9466 }
else if (!isa<CXXConstructorDecl>(NewFD) &&
9467 !isa<CXXConversionDecl>(NewFD)) {
9471 diag::err_explicit_non_ctor_or_conv_function)
9485 if (isa<CXXDestructorDecl>(NewFD) &&
9489 <<
static_cast<int>(ConstexprKind);
9503 diag::err_invalid_consteval_decl_kind)
9511 if (isFunctionTemplateSpecialization) {
9514 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9519 if (FunctionTemplate)
9525 if (FunctionTemplate) {
9549 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9557 if (SC ==
SC_Static && isa<CXXMethodDecl>(NewFD) &&
9558 !CurContext->isRecord()) {
9572 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9574 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9582 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9583 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9593 isMemberSpecialization ||
9594 isFunctionTemplateSpecialization);
9603 }
else if (!ExtnameUndeclaredIdentifiers.empty()) {
9604 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9606 if (I != ExtnameUndeclaredIdentifiers.end()) {
9609 ExtnameUndeclaredIdentifiers.erase(I);
9629 for (
unsigned i = 0, e = FTI.
NumParams; i != e; ++i) {
9633 Params.push_back(Param);
9648 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9653 if (
auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9654 TD = cast<EnumDecl>(ECD->getDeclContext());
9662 TD->setDeclContext(NewFD);
9670 if (TagDC != PrototypeTagContext)
9671 TD->setLexicalDeclContext(TagDC);
9685 for (
const auto &AI : FT->param_types()) {
9689 Params.push_back(Param);
9693 "Should not need args for typedef of non-prototype fn");
9697 NewFD->setParams(Params);
9700 NewFD->
addAttr(C11NoReturnAttr::Create(Context,
9714 !NewFD->
hasAttr<SectionAttr>())
9715 NewFD->
addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9716 Context, PragmaClangTextSection.SectionName,
9721 !NewFD->
hasAttr<SectionAttr>()) {
9722 NewFD->
addAttr(SectionAttr::CreateImplicit(
9723 Context, CodeSegStack.CurrentValue->getString(),
9725 SectionAttr::Declspec_allocate));
9726 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9735 if (!NewFD->
hasAttr<CodeSegAttr>()) {
9736 if (
Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9743 ProcessDeclAttributes(S, NewFD, D);
9745 if (getLangOpts().
OpenCL) {
9751 diag::err_opencl_return_value_with_address_space);
9762 CheckMSVCRTEntryPoint(NewFD);
9766 isMemberSpecialization));
9772 "previous declaration set still overloaded");
9784 CC ==
CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9794 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9807 diag::ext_operator_new_delete_declared_inline)
9818 translateTemplateArguments(TemplateArgsPtr,
9821 HasExplicitTemplateArgs =
true;
9824 HasExplicitTemplateArgs =
false;
9825 }
else if (FunctionTemplate) {
9830 HasExplicitTemplateArgs =
false;
9832 assert((isFunctionTemplateSpecialization ||
9834 "should have a 'template<>' for this decl");
9836 isFunctionTemplateSpecialization =
true;
9838 }
else if (isFriend && isFunctionTemplateSpecialization) {
9845 HasExplicitTemplateArgs =
true;
9856 if (getLangOpts().
CUDA && !isFunctionTemplateSpecialization)
9857 maybeAddCUDAHostDeviceAttrs(NewFD,
Previous);
9863 if (isFunctionTemplateSpecialization && isFriend &&
9867 assert(HasExplicitTemplateArgs &&
9868 "friend function specialization without template args");
9869 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9872 }
else if (isFunctionTemplateSpecialization) {
9873 if (CurContext->isDependentContext() && CurContext->isRecord()
9875 isDependentClassScopeExplicitSpecialization =
true;
9877 CheckFunctionTemplateSpecialization(
9878 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs :
nullptr),
9890 diag::err_explicit_specialization_inconsistent_storage_class)
9897 diag::ext_explicit_specialization_storage_class)
9901 }
else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9902 if (CheckMemberSpecialization(NewFD,
Previous))
9907 if (!isDependentClassScopeExplicitSpecialization) {
9912 CheckMSVCRTEntryPoint(NewFD);
9916 isMemberSpecialization));
9924 "previous declaration set still overloaded");
9926 NamedDecl *PrincipalDecl = (FunctionTemplate
9927 ? cast<NamedDecl>(FunctionTemplate)
9936 if (FunctionTemplate) FunctionTemplate->
setAccess(Access);
9945 if (FunctionTemplate) {
9953 ? TPC_FriendFunctionTemplateDefinition
9954 : TPC_FriendFunctionTemplate)
9958 ? TPC_ClassTemplateMember
9959 : TPC_FunctionTemplate);
9965 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9988 (!
Previous.empty() && CurContext->isDependentContext()))) {
10011 *
this,
Previous, NewFD, ExtraArgs,
false,
nullptr)) {
10012 AddToScope = ExtraArgs.AddToScope;
10019 }
else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10021 *
this,
Previous, NewFD, ExtraArgs,
true, S)) {
10022 AddToScope = ExtraArgs.AddToScope;
10027 isa<CXXMethodDecl>(NewFD) && NewFD->
isOutOfLine() &&
10028 !isFriend && !isFunctionTemplateSpecialization &&
10029 !isMemberSpecialization) {
10047 if (
unsigned BuiltinID = II->getBuiltinID()) {
10052 NewFD->
addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10055 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10061 NewFD->
addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10063 }
else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10066 NewFD->
addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10072 ProcessPragmaWeak(S, NewFD);
10075 AddKnownFunctionAttributes(NewFD);
10077 if (NewFD->
hasAttr<OverloadableAttr>() &&
10080 diag::err_attribute_overloadable_no_prototype)
10087 EPI.Variadic =
true;
10088 EPI.ExtInfo = FT->getExtInfo();
10097 AddPushedVisibilityAttribute(NewFD);
10101 AddCFAuditedAttribute(NewFD);
10106 AddRangeBasedOptnone(NewFD);
10112 RegisterLocallyScopedExternCDecl(NewFD, S);
10120 isMemberSpecialization ||
10121 isFunctionTemplateSpecialization,
10125 if (getLangOpts().
CUDA) {
10127 if (II && II->
isStr(getCudaConfigureFuncName()) &&
10132 << getCudaConfigureFuncName();
10139 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->
isVariadic() &&
10140 (NewFD->
hasAttr<CUDADeviceAttr>() ||
10141 NewFD->
hasAttr<CUDAGlobalAttr>()) &&
10148 MarkUnusedFileScopedDecl(NewFD);
10152 if (getLangOpts().
OpenCL && NewFD->
hasAttr<OpenCLKernelAttr>()) {
10172 if (getLangOpts().OpenCLCPlusPlus) {
10177 if (FunctionTemplate) {
10185 if (FunctionTemplate) {
10188 return FunctionTemplate;
10192 CompleteMemberSpecialization(NewFD,
Previous);
10199 QualType ElemTy = PipeTy->getElementType();
10201 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10210 if (isDependentClassScopeExplicitSpecialization) {
10214 cast<CXXMethodDecl>(NewFD),
10215 HasExplicitTemplateArgs, TemplateArgs);
10216 CurContext->addDecl(NewSpec);
10217 AddToScope =
false;
10222 if (
const auto *
attr = NewFD->
getAttr<AvailabilityAttr>()) {
10223 if (NewFD->
hasAttr<ConstructorAttr>()) {
10224 Diag(
attr->getLocation(), diag::warn_availability_on_static_initializer)
10226 NewFD->
dropAttr<AvailabilityAttr>();
10228 if (NewFD->
hasAttr<DestructorAttr>()) {
10229 Diag(
attr->getLocation(), diag::warn_availability_on_static_initializer)
10231 NewFD->
dropAttr<AvailabilityAttr>();
10242 if (
const auto *NBA = NewFD->
getAttr<NoBuiltinAttr>())
10246 Diag(NBA->getLocation(),
10247 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10248 << NBA->getSpelling();
10251 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10252 << NBA->getSpelling();
10272 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10276 if (
const auto *SAttr =
Parent->getAttr<CodeSegAttr>()) {
10287 while ((
Parent = dyn_cast<CXXRecordDecl>(
Parent->getParent()))) {
10288 if (
const auto *SAttr =
Parent->getAttr<CodeSegAttr>()) {
10307 bool IsDefinition) {
10310 if (!FD->
hasAttr<SectionAttr>() && IsDefinition &&
10311 CodeSegStack.CurrentValue)
10312 return SectionAttr::CreateImplicit(
10313 getASTContext(), CodeSegStack.CurrentValue->getString(),
10315 SectionAttr::Declspec_allocate);
10380 auto *VD = dyn_cast<ValueDecl>(D);
10381 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10382 return !VD || !PrevVD ||
10383 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10384 PrevVD->getType());
10392 const auto *TA = FD->
getAttr<TargetAttr>();
10393 assert(TA &&
"MultiVersion Candidate requires a target attribute");
10396 enum ErrType { Feature = 0, Architecture = 1 };
10405 for (
const auto &Feat : ParseInfo.
Features) {
10406 auto BareFeat = StringRef{Feat}.substr(1);
10407 if (Feat[0] ==
'-') {
10409 << Feature << (
"no-" + BareFeat).str();
10416 << Feature << BareFeat;
10434 case attr::NonNull:
10435 case attr::NoThrow:
10444 const auto Diagnose = [FD, CausedFD, MVKind](
Sema &S,
const Attr *A) {
10445 S.
Diag(FD->
getLocation(), diag::err_multiversion_disallowed_other_attr)
10446 <<
static_cast<unsigned>(MVKind) << A;
10448 S.
Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10453 switch (A->getKind()) {
10454 case attr::CPUDispatch:
10455 case attr::CPUSpecific:
10458 return Diagnose(S, A);
10462 return Diagnose(S, A);
10464 case attr::TargetClones:
10466 return Diagnose(S, A);
10470 return Diagnose(S, A);
10483 bool ConstexprSupported,
bool CLinkageMayDiffer) {
10484 enum DoesntSupport {
10491 DefaultedFuncs = 6,
10492 ConstexprFuncs = 7,
10493 ConstevalFuncs = 8,
10505 if (NoProtoDiagID.
getDiagID() != 0 && OldFD &&
10508 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10516 if (!TemplatesSupported &&
10518 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10521 if (
const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10522 if (NewCXXFD->isVirtual())
10523 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10526 if (isa<CXXConstructorDecl>(NewCXXFD))
10527 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10530 if (isa<CXXDestructorDecl>(NewCXXFD))
10531 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10536 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10540 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10544 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10545 << (NewFD->
isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10548 const auto *NewType = cast<FunctionType>(NewQType);
10549 QualType NewReturnType = NewType->getReturnType();
10552 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10558 const auto *OldType = cast<FunctionType>(OldQType);
10562 if (OldTypeInfo.
getCC() != NewTypeInfo.
getCC())
10565 QualType OldReturnType = OldType->getReturnType();
10567 if (OldReturnType != NewReturnType)
10568 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10571 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10574 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10577 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) <<
Linkage;
10582 if (CheckEquivalentExceptionSpec(
10601 bool IsCPUSpecificCPUDispatchMVKind =
10605 if (CausesMV && OldFD &&
10613 if (OldFD && CausesMV && OldFD->
isUsed(
false))
10614 return S.
Diag(NewFD->
getLocation(), diag::err_multiversion_after_used);
10617 OldFD, NewFD, S.
PDiag(diag::err_multiversion_noproto),
10619 S.
PDiag(diag::note_multiversioning_caused_here)),
10621 S.
PDiag(diag::err_multiversion_doesnt_support)
10622 <<
static_cast<unsigned>(MVKind)),
10624 S.
PDiag(diag::err_multiversion_diff)),
10626 !IsCPUSpecificCPUDispatchMVKind,
10638 const TargetAttr *TA) {
10640 "Function lacks multiversion attribute");
10673 const auto *OldTA = OldFD->
getAttr<TargetAttr>();
10676 llvm::sort(NewParsed.Features);
10680 if (!NewTA->isDefaultVersion() &&
10681 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10697 if (!OldFD->
isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10698 Redeclaration =
true;
10706 S.
Diag(NewFD->
getLocation(), diag::note_multiversioning_caused_here);
10713 if (OldParsed == NewParsed) {
10720 for (
const auto *FD : OldFD->
redecls()) {
10721 const auto *CurTA = FD->
getAttr<TargetAttr>();
10725 (!CurTA || CurTA->isInherited())) {
10728 S.
Diag(NewFD->
getLocation(), diag::note_multiversioning_caused_here);
10736 Redeclaration =
false;
10759 const CPUDispatchAttr *NewCPUDisp,
const CPUSpecificAttr *NewCPUSpec,
10760 const TargetClonesAttr *NewClones,
bool &Redeclaration,
NamedDecl *&OldDecl,
10774 NewParsed = NewTA->parse();
10778 bool UseMemberUsingDeclRules =
10781 bool MayNeedOverloadableChecks =
10790 if (MayNeedOverloadableChecks &&
10791 S.
IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10794 switch (NewMVKind) {
10797 "Only target_clones can be omitted in subsequent declarations");
10800 const auto *CurTA = CurFD->
getAttr<TargetAttr>();
10801 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10803 Redeclaration =
true;
10809 if (CurParsed == NewParsed) {
10818 const auto *CurClones = CurFD->
getAttr<TargetClonesAttr>();
10819 Redeclaration =
true;
10823 if (CurClones && NewClones &&
10824 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10825 !std::equal(CurClones->featuresStrs_begin(),
10826 CurClones->featuresStrs_end(),
10827 NewClones->featuresStrs_begin()))) {
10838 const auto *CurCPUSpec = CurFD->
getAttr<CPUSpecificAttr>();
10839 const auto *CurCPUDisp = CurFD->
getAttr<CPUDispatchAttr>();
10844 CurFD->
hasAttr<CPUDispatchAttr>()) {
10845 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10847 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10848 NewCPUDisp->cpus_begin(),
10850 return Cur->getName() == New->getName();
10853 Redeclaration =
true;
10865 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10867 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10868 NewCPUSpec->cpus_begin(),
10870 return Cur->getName() == New->getName();
10873 Redeclaration =
true;
10881 if (CurII == NewII) {
10915 Redeclaration =
true;
10921 Redeclaration =
false;
10934 bool &Redeclaration,
NamedDecl *&OldDecl,
10936 const auto *NewTA = NewFD->
getAttr<TargetAttr>();
10937 const auto *NewCPUDisp = NewFD->
getAttr<CPUDispatchAttr>();
10938 const auto *NewCPUSpec = NewFD->
getAttr<CPUSpecificAttr>();
10939 const auto *NewClones = NewFD->
getAttr<TargetClonesAttr>();
10947 S.
Diag(NewFD->
getLocation(), diag::err_multiversion_not_allowed_on_main);
10973 S.
Diag(NewFD->
getLocation(), diag::err_multiversion_required_in_redecl)
10983 Redeclaration, OldDecl,
Previous);
10985 if (OldFD->
isUsed(
false)) {
10987 return S.
Diag(NewFD->
getLocation(), diag::err_multiversion_after_used);
11002 NewCPUDisp, NewCPUSpec, NewClones,
11003 Redeclaration, OldDecl,
Previous);
11025 bool IsMemberSpecialization) {
11027 "Variably modified return types are not handled here");
11032 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11035 bool Redeclaration =
false;
11037 bool MayNeedOverloadableChecks =
false;
11048 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11049 Redeclaration =
true;
11050 OldDecl = Candidate;
11053 MayNeedOverloadableChecks =
true;
11054 switch (CheckOverload(S, NewFD,
Previous, OldDecl,
11057 Redeclaration =
true;
11060 case Ovl_NonFunction:
11061 Redeclaration =
true;
11065 Redeclaration =
false;
11072 if (!Redeclaration &&
11077 Redeclaration =
true;
11078 OldDecl =
Previous.getFoundDecl();
11079 MergeTypeWithPrevious =
false;
11082 if (OldDecl->
hasAttr<OverloadableAttr>() ||
11083 NewFD->
hasAttr<OverloadableAttr>()) {
11084 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl),
false)) {
11085 MayNeedOverloadableChecks =
true;
11086 Redeclaration =
false;
11094 return Redeclaration;
11113 !MD->
isStatic() && !isa<CXXConstructorDecl>(MD) &&
11117 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->
getAsFunction());
11118 if (!OldMD || !OldMD->
isStatic()) {
11128 if (!inTemplateInstantiation()) {
11132 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11140 if (Redeclaration) {
11143 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11145 return Redeclaration;
11152 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11153 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11156 assert(NewTemplateDecl &&
"Template/non-template mismatch");
11165 NewFD->
setAccess(OldTemplateDecl->getAccess());
11166 NewTemplateDecl->
setAccess(OldTemplateDecl->getAccess());
11171 if (IsMemberSpecialization &&
11174 assert(OldTemplateDecl->isMemberSpecialization());
11177 if (OldFD->isDeleted()) {
11179 assert(OldFD->getCanonicalDecl() == OldFD);
11181 OldFD->setDeletedAsWritten(
false);
11186 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11187 auto *OldFD = cast<FunctionDecl>(OldDecl);
11194 }
else if (!getLangOpts().
CPlusPlus && MayNeedOverloadableChecks &&
11195 !NewFD->
getAttr<OverloadableAttr>()) {
11199 return ND->hasAttr<OverloadableAttr>();
11201 "Non-redecls shouldn't happen without overloadable present");
11204 const auto *FD = dyn_cast<FunctionDecl>(ND);
11205 return FD && !FD->
hasAttr<OverloadableAttr>();
11208 if (OtherUnmarkedIter !=
Previous.end()) {
11210 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11211 Diag((*OtherUnmarkedIter)->getLocation(),
11212 diag::note_attribute_overloadable_prev_overload)
11215 NewFD->
addAttr(OverloadableAttr::CreateImplicit(Context));
11219 if (LangOpts.OpenMP)
11220 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11227 CheckConstructor(Constructor);
11229 dyn_cast<CXXDestructorDecl>(NewFD)) {
11242 return Redeclaration;
11245 }
else if (
auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11246 if (
auto *TD = Guide->getDescribedFunctionTemplate())
11247 CheckDeductionGuideTemplate(TD);
11252 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11257 if (
CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11258 if (!Method->isFunctionTemplateSpecialization() &&
11259 !Method->getDescribedFunctionTemplate() &&
11260 Method->isCanonicalDecl()) {
11261 AddOverriddenMethods(Method->getParent(), Method);
11267 diag::err_constrained_virtual_method);
11269 if (Method->isStatic())
11270 checkThisInStaticMemberFunctionType(Method);
11274 ActOnConversionDeclarator(Conversion);
11278 CheckOverloadedOperatorDeclaration(NewFD)) {
11280 return Redeclaration;
11285 CheckLiteralOperatorDeclaration(NewFD)) {
11287 return Redeclaration;
11293 if (!CurContext->isRecord())
11294 CheckCXXDefaultArguments(NewFD);
11305 else if (!R.isPODType(Context) && !R->isVoidType() &&
11306 !R->isObjCObjectPointerType())
11307 Diag(NewFD->
getLocation(), diag::warn_return_value_udt) << NewFD << R;
11320 auto HasNoexcept = [&](
QualType T) ->
bool {
11325 T = RT->getPointeeType();
11326 else if (T->isAnyPointerType())
11327 T = T->getPointeeType();
11329 T = MPT->getPointeeType();
11331 if (FPT->isNothrow())
11337 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11338 for (
QualType T : FPT->param_types())
11339 AnyNoexcept |= HasNoexcept(T);
11342 diag::warn_cxx17_compat_exception_spec_in_signature)
11346 if (!Redeclaration && LangOpts.CUDA)
11347 checkCUDATargetOverload(NewFD,
Previous);
11349 return Redeclaration;
11362 ? diag::err_static_main : diag::warn_static_main)
11369 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11370 Diag(NoreturnLoc, diag::ext_noreturn_main);
11371 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11381 if (getLangOpts().
OpenCL) {
11383 << FD->
hasAttr<OpenCLKernelAttr>();
11389 assert(T->
isFunctionType() &&
"function decl is not of function type");
11399 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11411 Diag(RTRange.
getBegin(), diag::note_main_change_return_type)
11433 if (isa<FunctionNoProtoType>(FT))
return;
11439 bool HasExtraParameters = (nparams > 3);
11451 HasExtraParameters =
false;
11453 if (HasExtraParameters) {
11466 for (
unsigned i = 0; i < nparams; ++i) {
11469 bool mismatch =
true;
11486 mismatch = !qs.
empty();
11515 if (T.isWindowsGNUEnvironment())
11520 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11528 assert(T->
isFunctionType() &&
"function decl is not of function type");
11537 if (FD->
getName() !=
"DllMain")
11541 if (!hasExplicitCallingConv(T)) {
11571 if (Init->isValueDependent()) {
11572 assert(Init->containsErrors() &&
11573 "Dependent code should only occur in error-recovery path.");
11576 const Expr *Culprit;
11577 if (Init->isConstantInitializer(Context,
false, &Culprit))
11579 Diag(Culprit->
getExprLoc(), diag::err_init_element_not_constant)
11587 class SelfReferenceChecker
11593 bool isReferenceType;
11601 SelfReferenceChecker(
Sema &S,
Decl *OrigDecl) : Inherited(S.Context),
11602 S(S), OrigDecl(OrigDecl) {
11605 isReferenceType =
false;
11606 isInitList =
false;
11607 if (
ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11608 isPODType = VD->getType().isPODType(S.
Context);
11610 isReferenceType = VD->getType()->isReferenceType();
11617 void CheckExpr(
Expr *E) {
11626 InitFieldIndex.push_back(0);
11627 for (
auto Child : InitList->
children()) {
11628 CheckExpr(cast<Expr>(Child));
11629 ++InitFieldIndex.back();
11631 InitFieldIndex.pop_back();
11636 bool CheckInitListMemberExpr(
MemberExpr *E,
bool CheckReference) {
11639 bool ReferenceField =
false;
11643 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11646 Fields.push_back(FD);
11648 ReferenceField =
true;
11649 Base = ME->getBase()->IgnoreParenImpCasts();
11654 if (!DRE || DRE->
getDecl() != OrigDecl)
11658 if (CheckReference && !ReferenceField)
11663 for (
const FieldDecl *I : llvm::reverse(Fields))
11664 UsedFieldIndex.push_back(I->getFieldIndex());
11669 for (
auto UsedIter = UsedFieldIndex.begin(),
11670 UsedEnd = UsedFieldIndex.end(),
11671 OrigIter = InitFieldIndex.begin(),
11672 OrigEnd = InitFieldIndex.end();
11673 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11674 if (*UsedIter < *OrigIter)
11676 if (*UsedIter > *OrigIter)
11681 HandleDeclRefExpr(DRE);
11688 void HandleValue(
Expr *E) {
11690 if (
DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11691 HandleDeclRefExpr(DRE);
11696 Visit(CO->getCond());
11697 HandleValue(CO->getTrueExpr());
11698 HandleValue(CO->getFalseExpr());
11703 dyn_cast<BinaryConditionalOperator>(E)) {
11704 Visit(BCO->getCond());
11705 HandleValue(BCO->getFalseExpr());
11710 HandleValue(OVE->getSourceExpr());
11715 if (BO->getOpcode() == BO_Comma) {
11716 Visit(BO->getLHS());
11717 HandleValue(BO->getRHS());
11722 if (isa<MemberExpr>(E)) {
11724 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11732 if (!isa<FieldDecl>(ME->getMemberDecl()))
11734 Base = ME->getBase()->IgnoreParenImpCasts();
11737 HandleDeclRefExpr(DRE);
11747 if (isReferenceType)
11748 HandleDeclRefExpr(E);
11757 Inherited::VisitImplicitCastExpr(E);
11762 if (CheckInitListMemberExpr(E,
true ))
11772 bool Warn = (MD && !MD->
isStatic());
11775 if (!isa<FieldDecl>(ME->getMemberDecl()))
11777 Base = ME->getBase()->IgnoreParenImpCasts();
11782 HandleDeclRefExpr(DRE);
11794 if (isa<UnresolvedLookupExpr>(Callee))
11795 return Inherited::VisitCXXOperatorCallExpr(E);
11799 HandleValue(Arg->IgnoreParenImpCasts());
11816 Inherited::VisitUnaryOperator(E);
11824 if (
InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11825 if (ILE->getNumInits() == 1)
11826 ArgExpr = ILE->getInit(0);
11828 if (ICE->getCastKind() == CK_NoOp)
11829 ArgExpr = ICE->getSubExpr();
11830 HandleValue(ArgExpr);
11833 Inherited::VisitCXXConstructExpr(E);
11839 HandleValue(E->
getArg(0));
11843 Inherited::VisitCallExpr(E);
11848 HandleValue(E->
getLHS());
11853 Inherited::VisitBinaryOperator(E);
11866 if (OrigDecl != ReferenceDecl)
return;
11868 if (isReferenceType) {
11869 diag = diag::warn_uninit_self_reference_in_reference_init;
11870 }
else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11871 diag = diag::warn_static_self_reference_in_init;
11872 }
else if (isa<TranslationUnitDecl>(OrigDecl->
getDeclContext()) ||
11875 diag = diag::warn_uninit_self_reference_in_init;
11889 static void CheckSelfReference(
Sema &S,
Decl* OrigDecl,
Expr *E,
11893 if (isa<ParmVarDecl>(OrigDecl))
11900 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->
isRecordType())
11902 if (ICE->getCastKind() == CK_LValueToRValue)
11903 if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11904 if (DRE->
getDecl() == OrigDecl)
11907 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11914 struct VarDeclOrName {
11920 return VN.VDecl ?
Diag << VN.VDecl :
Diag << VN.Name;
11930 bool IsInitCapture = !VDecl;
11932 "init captures are expected to be deduced prior to initialization");
11934 VarDeclOrName VN{VDecl, Name};
11937 assert(Deduced &&
"deduceVarTypeFromInitializer for non-deduced type");
11941 assert(VDecl &&
"no init for init capture deduction?");
11945 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11956 DeduceInits = Init;
11959 if (
auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11960 DeduceInits = PL->exprs();
11963 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11964 assert(VDecl &&
"non-auto type for init capture deduction?");
11970 return DeduceTemplateSpecializationFromInitializer(TSI, Entity,
Kind,
11975 if (
auto *IL = dyn_cast<InitListExpr>(Init))
11976 DeduceInits = IL->inits();
11980 if (DeduceInits.empty()) {
11983 Diag(Init->getBeginLoc(), IsInitCapture
11984 ? diag::err_init_capture_no_expression
11985 : diag::err_auto_var_init_no_expression)
11986 << VN <<
Type << Range;
11990 if (DeduceInits.size() > 1) {
11991 Diag(DeduceInits[1]->getBeginLoc(),
11992 IsInitCapture ? diag::err_init_capture_multiple_expressions
11993 : diag::err_auto_var_init_multiple_expressions)
11994 << VN <<
Type << Range;
11998 Expr *DeduceInit = DeduceInits[0];
11999 if (
DirectInit && isa<InitListExpr>(DeduceInit)) {
12000 Diag(Init->getBeginLoc(), IsInitCapture
12001 ? diag::err_init_capture_paren_braces
12002 : diag::err_auto_var_init_paren_braces)
12003 << isa<InitListExpr>(Init) << VN <<
Type << Range;
12008 bool DefaultedAnyToId =
false;
12009 if (getLangOpts().DebuggerCastResultToId &&
12010 Init->getType() == Context.
UnknownAnyTy && !IsInitCapture) {
12012 if (Result.isInvalid()) {
12015 Init = Result.get();
12016 DefaultedAnyToId =
true;
12022 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12026 Type.getQualifiers());
12029 if (DeduceAutoType(TSI, DeduceInit,
DeducedType) == DAR_Failed) {
12030 if (!IsInitCapture)
12031 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12032 else if (isa<InitListExpr>(Init))
12033 Diag(Range.getBegin(),
12034 diag::err_init_capture_deduction_failure_from_init_list)
12040 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12052 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12055 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12063 assert(!Init || !Init->containsErrors());
12076 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12079 if (getLangOpts().
OpenCL)
12080 deduceOpenCLAddressSpace(VDecl);
12087 MergeVarDeclTypes(VDecl, Old,
false);
12091 CheckVariableDeclarationType(VDecl);
12097 if (
auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12098 Init = EWC->getSubExpr();
12100 if (
auto *CE = dyn_cast<ConstantExpr>(Init))
12101 Init = CE->getSubExpr();
12103 QualType InitType = Init->getType();
12106 "shouldn't be called if type doesn't have a non-trivial C struct");
12107 if (
auto *ILE = dyn_cast<InitListExpr>(Init)) {
12108 for (
auto I : ILE->inits()) {
12109 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12110 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12113 checkNonTrivialCUnionInInitializer(I, SL.
isValid() ? SL : Loc);
12118 if (isa<ImplicitValueInitExpr>(Init)) {
12120 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12128 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12134 bool shouldIgnoreForRecordTriviality(
const FieldDecl *FD) {
12140 return FD->
hasAttr<UnavailableAttr>();
12143 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12150 DiagNonTrivalCUnionDefaultInitializeVisitor(
12153 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12156 const FieldDecl *FD,
bool InNonTrivialUnion) {
12159 InNonTrivialUnion);
12160 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12164 bool InNonTrivialUnion) {
12165 if (InNonTrivialUnion)
12167 << 1 << 0 << QT << FD->
getName();
12171 if (InNonTrivialUnion)
12173 << 1 << 0 << QT << FD->
getName();
12179 if (OrigLoc.isValid()) {
12180 bool IsUnion =
false;
12181 if (
auto *OrigRD = OrigTy->getAsRecordDecl())
12182 IsUnion = OrigRD->isUnion();
12183 S.
Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12184 << 0 << OrigTy << IsUnion << UseContext;
12188 InNonTrivialUnion =
true;
12191 if (InNonTrivialUnion)
12196 if (!shouldIgnoreForRecordTriviality(FD))
12197 asDerived().visit(FD->
getType(), FD, InNonTrivialUnion);
12210 struct DiagNonTrivalCUnionDestructedTypeVisitor
12215 DiagNonTrivalCUnionDestructedTypeVisitor(
12218 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12221 const FieldDecl *FD,
bool InNonTrivialUnion) {
12224 InNonTrivialUnion);
12225 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12229 bool InNonTrivialUnion) {
12230 if (InNonTrivialUnion)
12232 << 1 << 1 << QT << FD->
getName();
12236 if (InNonTrivialUnion)
12238 << 1 << 1 << QT << FD->
getName();
12244 if (OrigLoc.isValid()) {
12245 bool IsUnion =
false;
12246 if (
auto *OrigRD = OrigTy->getAsRecordDecl())
12247 IsUnion = OrigRD->isUnion();
12248 S.
Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12249 << 1 << OrigTy << IsUnion << UseContext;
12253 InNonTrivialUnion =
true;
12256 if (InNonTrivialUnion)
12261 if (!shouldIgnoreForRecordTriviality(FD))
12262 asDerived().visit(FD->
getType(), FD, InNonTrivialUnion);
12267 bool InNonTrivialUnion) {}
12277 struct DiagNonTrivalCUnionCopyVisitor
12284 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12287 const FieldDecl *FD,
bool InNonTrivialUnion) {
12290 InNonTrivialUnion);
12291 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12295 bool InNonTrivialUnion) {
12296 if (InNonTrivialUnion)
12298 << 1 << 2 << QT << FD->
getName();
12302 if (InNonTrivialUnion)
12304 << 1 << 2 << QT << FD->
getName();
12310 if (OrigLoc.isValid()) {
12311 bool IsUnion =
false;
12312 if (
auto *OrigRD = OrigTy->getAsRecordDecl())
12313 IsUnion = OrigRD->isUnion();
12314 S.
Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12315 << 2 << OrigTy << IsUnion << UseContext;
12319 InNonTrivialUnion =
true;
12322 if (InNonTrivialUnion)
12327 if (!shouldIgnoreForRecordTriviality(FD))
12328 asDerived().visit(FD->
getType(), FD, InNonTrivialUnion);
12332 const FieldDecl *FD,
bool InNonTrivialUnion) {}
12335 bool InNonTrivialUnion) {}
12349 unsigned NonTrivialKind) {
12353 "shouldn't be called if type doesn't have a non-trivial C union");
12355 if ((NonTrivialKind & NTCUK_Init) &&
12357 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *
this)
12358 .
visit(QT,
nullptr,
false);
12359 if ((NonTrivialKind & NTCUK_Destruct) &&
12361 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *
this)
12362 .visit(QT,
nullptr,
false);
12364 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *
this)
12365 .visit(QT,
nullptr,
false);
12375 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12379 if (
CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12381 Diag(Method->getLocation(), diag::err_member_function_initialization)
12382 << Method->getDeclName() << Init->getSourceRange();
12383 Method->setInvalidDecl();
12387 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12389 assert(!isa<FieldDecl>(RealDecl) &&
"field init shouldn't get here");
12400 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12415 if (DeduceVariableDeclarationType(VDecl,
DirectInit, Init))
12421 Diag(VDecl->
getLocation(), diag::err_attribute_dllimport_data_definition);
12439 BaseDeclType =
Array->getElementType();
12440 if (RequireCompleteType(VDecl->
getLocation(), BaseDeclType,
12441 diag::err_typecheck_decl_incomplete_type)) {
12448 diag::err_abstract_type_in_decl,
12449 AbstractVariableType))
12457 if (Def != VDecl &&
12460 checkVarDeclRedefinition(Def, VDecl))
12477 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12480 diag::note_previous_initializer)
12486 setFunctionHasBranchProtectedScope();
12488 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12503 if (isSYCLEsimdPrivateGlobal(VDecl)) {
12510 if (VDecl->
hasAttr<LoaderUninitializedAttr>()) {
12511 Diag(VDecl->
getLocation(), diag::err_loader_uninitialized_cant_init);
12525 if (Result.isInvalid()) {
12529 Init = Result.get();
12533 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12545 for (
size_t Idx = 0; Idx < Args.size(); ++Idx) {
12547 Args[Idx], VDecl,
true,
12550 return Init.Failed() ?
ExprError() : E;
12554 }
else if (Res.
get() != Args[Idx]) {
12555 Args[Idx] = Res.
get();
12565 if (Result.isInvalid()) {
12569 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12575 Init = Result.getAs<
Expr>();
12582 if (getLangOpts().CPlusPlus)
12585 CheckSelfReference(*
this, RealDecl, Init,
DirectInit);
12597 if (VDecl->
hasAttr<BlocksAttr>())
12598 checkRetainCycles(VDecl, Init);
12610 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12611 Init->getBeginLoc()))
12612 FSI->markSafeWeakUse(Init);
12629 if (Result.isInvalid()) {
12633 Init = Result.get();
12646 CheckForConstantInitializer(Init, DclT);
12655 CheckForConstantInitializer(Init, DclT);
12662 isa<InitListExpr>(Init)) {
12663 const Expr *Culprit;
12664 if (!Init->isConstantInitializer(Context,
false, &Culprit)) {
12666 diag::ext_aggregate_init_not_constant)
12671 if (
auto *E = dyn_cast<ExprWithCleanups>(Init))
12672 if (
auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->
IgnoreParens()))
12674 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12709 << Init->getSourceRange();
12720 else if (Init->isValueDependent())
12722 else if (Init->isIntegerConstantExpr(Context, &Loc))
12724 else if (Init->getType()->isScopedEnumeralType() &&
12725 Init->isCXX11ConstantExpr(Context))
12727 else if (Init->isEvaluatable(Context)) {
12730 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12731 << Init->getSourceRange();
12735 Diag(Loc, diag::err_in_class_initializer_non_constant)
12736 << Init->getSourceRange();
12746 diag::ext_in_class_initializer_float_type_cxx11)
12747 << DclT << Init->getSourceRange();
12749 diag::note_in_class_initializer_float_type_cxx11)
12752 Diag(VDecl->
getLocation(), diag::ext_in_class_initializer_float_type)
12753 << DclT << Init->getSourceRange();
12755 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12756 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12757 << Init->getSourceRange();
12764 Diag(VDecl->
getLocation(), diag::err_in_class_initializer_literal_type)
12765 << DclT << Init->getSourceRange()
12771 << DclT << Init->getSourceRange();
12799 CheckForConstantInitializer(Init, DclT);
12802 QualType InitType = Init->getType();
12803 if (!InitType.
isNull() &&
12806 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12822 if (CXXDirectInit) {
12823 assert(
DirectInit &&
"Call-style initializer must be direct init.");
12830 if (LangOpts.OpenMP &&
12831 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12833 DeclsToCheckForDeferredDiags.insert(VDecl);
12834 CheckCompleteVariableDeclaration(VDecl);
12846 VarDecl *VD = dyn_cast<VarDecl>(D);
12850 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
12851 for (
auto *BD : DD->bindings())
12852 BD->setInvalidDecl();
12866 diag::err_typecheck_decl_incomplete_type)) {
12872 if (RequireNonAbstractType(VD->
getLocation(), Ty,
12873 diag::err_abstract_type_in_decl,
12874 AbstractVariableType)) {
12888 if (
VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12892 if (isa<DecompositionDecl>(RealDecl)) {
12893 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12894 Var->setInvalidDecl();
12899 DeduceVariableDeclarationType(Var,
false,
nullptr))
12908 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12909 !Var->isThisDeclarationADemotedDefinition()) {
12910 if (Var->isStaticDataMember()) {
12915 Diag(Var->getLocation(),
12916 diag::err_constexpr_static_mem_var_requires_init)
12918 Var->setInvalidDecl();
12922 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12923 Var->setInvalidDecl();
12930 if (!Var->isInvalidDecl() &&
12932 Var->getStorageClass() !=
SC_Extern && !Var->getInit()) {
12933 bool HasConstExprDefaultConstructor =
false;
12934 if (
CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12935 for (
auto *Ctor : RD->ctors()) {
12936 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12937 Ctor->getMethodQualifiers().getAddressSpace() ==
12939 HasConstExprDefaultConstructor =
true;
12943 if (!HasConstExprDefaultConstructor) {
12944 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12945 Var->setInvalidDecl();
12950 if (!Var->isInvalidDecl() && RealDecl->
hasAttr<LoaderUninitializedAttr>()) {
12951 if (Var->getStorageClass() ==
SC_Extern) {
12952 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12954 Var->setInvalidDecl();
12957 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12958 diag::err_typecheck_decl_incomplete_type)) {
12959 Var->setInvalidDecl();
12962 if (
CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12963 if (!RD->hasTrivialDefaultConstructor()) {
12964 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12965 Var->setInvalidDecl();
12975 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12976 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12977 NTCUC_DefaultInitializedObject, NTCUK_Init);
12982 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12998 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12999 RequireCompleteType(Var->getLocation(),
Type,
13000 diag::err_typecheck_decl_incomplete_type))
13001 Var->setInvalidDecl();
13005 RequireNonAbstractType(Var->getLocation(),
Type,
13006 diag::err_abstract_type_in_decl,
13007 AbstractVariableType))
13008 Var->setInvalidDecl();
13011 Diag(Var->getLocation(), diag::warn_private_extern);
13012 Diag(Var->getLocation(), diag::note_private_extern);
13016 !Var->isInvalidDecl() && !getLangOpts().
CPlusPlus)
13017 ExternalDeclarations.push_back(Var);
13027 if (!Var->isInvalidDecl()) {
13030 if (RequireCompleteSizedType(
13031 Var->getLocation(), ArrayT->getElementType(),
13032 diag::err_array_incomplete_or_sizeless_type))
13033 Var->setInvalidDecl();
13034 }
else if (Var->getStorageClass() ==
SC_Static) {
13044 if (Var->isFirstDecl())
13045 RequireCompleteType(Var->getLocation(),
Type,
13046 diag::ext_typecheck_decl_incomplete_type);
13051 if (!Var->isInvalidDecl())
13052 TentativeDefinitions.push_back(Var);
13059 Diag(Var->getLocation(),
13060 diag::err_typecheck_incomplete_array_needs_initializer);
13061 Var->setInvalidDecl();
13068 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13069 << Var <<
SourceRange(Var->getLocation(), Var->getLocation());
13070 Var->setInvalidDecl();
13079 if (Var->isInvalidDecl())
13082 if (!Var->hasAttr<AliasAttr>()) {
13083 if (RequireCompleteType(Var->getLocation(),
13085 diag::err_typecheck_decl_incomplete_type)) {
13086 Var->setInvalidDecl();
13094 if (RequireNonAbstractType(Var->getLocation(),
Type,
13095 diag::err_abstract_type_in_decl,
13096 AbstractVariableType)) {
13097 Var->setInvalidDecl();
13111 if (getLangOpts().
CPlusPlus && Var->hasLocalStorage()) {
13114 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13118 if (!CXXRecord->isPOD())
13119 setFunctionHasBranchProtectedScope();
13124 if (getLangOpts().
OpenCL &&
13129 if (isSYCLEsimdPrivateGlobal(Var))
13154 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13157 }
else if (Init.isInvalid()) {
13161 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13166 CheckCompleteVariableDeclaration(Var);
13175 VarDecl *VD = dyn_cast<VarDecl>(D);
13234 const char *PrevSpec;
13237 getPrintingPolicy());
13245 Decl *Var = ActOnDeclarator(S, D);
13246 cast<VarDecl>(Var)->setCXXForRangeDecl(
true);
13247 FinalizeDeclaration(Var);
13248 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13254 if (
var->isInvalidDecl())
return;
13256 MaybeAddCUDAConstantAttr(
var);
13258 if (getLangOpts().
OpenCL) {
13261 if (
var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13263 Diag(
var->getLocation(), diag::err_opencl_invalid_block_declaration)
13265 var->setInvalidDecl();
13270 if (getLangOpts().SYCLIsDevice)
13271 checkSYCLDeviceVarDecl(
var);
13275 if (getLangOpts().ObjC &&
13276 var->hasLocalStorage()) {
13277 switch (
var->getType().getObjCLifetime()) {
13285 setFunctionHasBranchProtectedScope();
13290 if (
var->hasLocalStorage() &&
13292 setFunctionHasBranchProtectedScope();
13299 if (
var->isThisDeclarationADefinition() &&
13300 var->getDeclContext()->getRedeclContext()->isFileContext() &&
13301 var->isExternallyVisible() &&
var->hasLinkage() &&
13302 !
var->isInline() && !
var->getDescribedVarTemplate() &&
13303 !isa<VarTemplatePartialSpecializationDecl>(
var) &&
13305 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13306 var->getLocation())) {
13313 Diag(
var->getLocation(), diag::warn_missing_variable_declarations) <<
var;
13314 Diag(
var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13321 const Expr *CacheCulprit =
nullptr;
13322 auto checkConstInit = [&]()
mutable {
13323 if (!CacheHasConstInit)
13324 CacheHasConstInit =
var->getInit()->isConstantInitializer(
13325 Context,
var->getType()->isReferenceType(), &CacheCulprit);
13326 return *CacheHasConstInit;
13330 if (
var->getType().isDestructedType()) {
13334 Diag(
var->getLocation(), diag::err_thread_nontrivial_dtor);
13336 Diag(
var->getLocation(), diag::note_use_thread_local);
13337 }
else if (getLangOpts().
CPlusPlus &&
var->hasInit()) {
13338 if (!checkConstInit()) {
13346 Diag(
var->getLocation(), diag::note_use_thread_local);
13352 if (!
var->getType()->isStructureType() &&
var->hasInit() &&
13353 isa<InitListExpr>(
var->getInit())) {
13354 const auto *ILE = cast<InitListExpr>(
var->getInit());
13355 unsigned NumInits = ILE->getNumInits();
13357 for (
unsigned I = 0; I < NumInits; ++I) {
13358 const auto *Init = ILE->getInit(I);
13361 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13365 unsigned NumConcat = SL->getNumConcatenated();
13369 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13370 bool OnlyOneMissingComma =
true;
13371 for (
unsigned J = I + 1; J < NumInits; ++J) {
13372 const auto *Init = ILE->getInit(J);
13375 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13376 if (!SLJ || SLJ->getNumConcatenated() > 1) {
13377 OnlyOneMissingComma =
false;
13382 if (OnlyOneMissingComma) {
13384 for (
unsigned i = 0; i < NumConcat - 1; ++i)
13386 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)),
","));
13388 Diag(SL->getStrTokenLoc(1),
13389 diag::warn_concatenated_literal_array_init)
13391 Diag(SL->getBeginLoc(),
13392 diag::note_concatenated_string_literal_silence);
13403 if (
var->hasAttr<BlocksAttr>())
13404 getCurFunction()->addByrefBlockVar(
var);
13407 bool GlobalStorage =
var->hasGlobalStorage();
13408 bool IsGlobal = GlobalStorage && !
var->isStaticLocal();
13410 bool HasConstInit =
true;
13413 if (getLangOpts().
CPlusPlus && !
type->isDependentType() && Init &&
13414 !Init->isValueDependent() &&
13415 (GlobalStorage ||
var->isConstexpr() ||
13416 var->mightBeUsableInConstantExpressions(Context))) {
13428 HasConstInit = checkConstInit();
13432 if (HasConstInit) {
13433 (void)
var->checkForConstantInitialization(Notes);
13435 }
else if (CacheCulprit) {
13436 Notes.emplace_back(CacheCulprit->
getExprLoc(),
13437 PDiag(diag::note_invalid_subexpr_in_const_expr));
13442 HasConstInit =
var->checkForConstantInitialization(Notes);
13445 if (HasConstInit) {
13447 }
else if (
var->isConstexpr()) {
13451 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13452 diag::note_invalid_subexpr_in_const_expr) {
13453 DiagLoc = Notes[0].first;
13456 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13457 <<
var << Init->getSourceRange();
13458 for (
unsigned I = 0, N = Notes.size(); I != N; ++I)
13459 Diag(Notes[I].first, Notes[I].second);
13460 }
else if (GlobalStorage &&
var->hasAttr<ConstInitAttr>()) {
13461 auto *
Attr =
var->getAttr<ConstInitAttr>();
13462 Diag(
var->getLocation(), diag::err_require_constant_init_failed)
13463 << Init->getSourceRange();
13466 for (
auto &it : Notes)
13467 Diag(it.first, it.second);
13468 }
else if (IsGlobal &&
13469 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13470 var->getLocation())) {
13479 if (!checkConstInit())
13480 Diag(
var->getLocation(), diag::warn_global_constructor)
13481 << Init->getSourceRange();
13487 if (GlobalStorage &&
var->isThisDeclarationADefinition() &&
13488 !inTemplateInstantiation()) {
13491 if (
var->getType().isConstQualified()) {
13493 Stack = &ConstSegStack;
13495 Stack = &BSSSegStack;
13498 }
else if (
var->hasInit() && HasConstInit) {
13499 Stack = &DataSegStack;
13502 Stack = &BSSSegStack;
13505 if (
const SectionAttr *SA =
var->getAttr<SectionAttr>()) {
13508 UnifySection(SA->getName(), SectionFlags,
var);
13509 }
else if (Stack->CurrentValue) {
13511 auto SectionName = Stack->CurrentValue->getString();
13512 var->addAttr(SectionAttr::CreateImplicit(
13513 Context, SectionName, Stack->CurrentPragmaLocation,
13515 if (UnifySection(SectionName, SectionFlags,
var))
13516 var->dropAttr<SectionAttr>();
13522 if (CurInitSeg &&
var->getInit())
13523 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13529 if (!getLangOpts().CPlusPlus) {
13538 if (!
type->isDependentType())
13548 if (
auto *DD = dyn_cast<DecompositionDecl>(
var))
13549 CheckCompleteDecompositionDeclaration(DD);
13561 !FD->
hasAttr<DLLExportStaticLocalAttr>() &&
13562 !FD->
hasAttr<DLLImportStaticLocalAttr>()) {
13571 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13572 NewAttr->setInherited(
true);
13574 }
else if (
Attr *A = FD->
getAttr<DLLExportStaticLocalAttr>()) {
13575 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13576 NewAttr->setInherited(
true);
13581 if (!FD->
hasAttr<DLLExportAttr>())
13584 }
else if (
Attr *A = FD->
getAttr<DLLImportStaticLocalAttr>()) {
13585 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13586 NewAttr->setInherited(
true);
13595 ParsingInitForAutoVars.erase(ThisDecl);
13597 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13603 !inTemplateInstantiation() && !VD->
hasAttr<SectionAttr>()) {
13604 if (PragmaClangBSSSection.Valid)
13605 VD->
addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13606 Context, PragmaClangBSSSection.SectionName,
13607 PragmaClangBSSSection.PragmaLocation,
13609 if (PragmaClangDataSection.Valid)
13610 VD->
addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13611 Context, PragmaClangDataSection.SectionName,
13612 PragmaClangDataSection.PragmaLocation,
13614 if (PragmaClangRodataSection.Valid)
13615 VD->
addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13616 Context, PragmaClangRodataSection.SectionName,
13617 PragmaClangRodataSection.PragmaLocation,
13619 if (PragmaClangRelroSection.Valid)
13620 VD->
addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13621 Context, PragmaClangRelroSection.SectionName,
13622 PragmaClangRelroSection.PragmaLocation,
13626 if (
auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13627 for (
auto *BD : DD->bindings()) {
13628 FinalizeDeclaration(BD);
13651 CheckStaticLocalForDllExport(VD);
13658 if (getLangOpts().CUDA)
13659 checkAllowedCUDAInitializer(VD);
13665 if (
const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13672 bool IsClassTemplateMember =
13673 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13674 Context->getDescribedClassTemplate();
13677 IsClassTemplateMember
13678 ? diag::warn_attribute_dllimport_static_field_definition
13679 : diag::err_attribute_dllimport_static_field_definition);
13680 Diag(IA->getLocation(), diag::note_attribute);
13681 if (!IsClassTemplateMember)
13709 if (RetainAttr *
Attr = VD->
getAttr<RetainAttr>()) {
13721 AddPushedVisibilityAttribute(VD);
13724 if (VD->
isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13725 MarkUnusedFileScopedDecl(VD);
13729 if (!VD->
hasAttr<TypeTagForDatatypeAttr>() ||
13733 for (
const auto *I : ThisDecl->
specific_attrs<TypeTagForDatatypeAttr>()) {
13735 if (!MagicValueExpr) {
13740 Diag(I->getRange().getBegin(),
13741 diag::err_type_tag_for_datatype_not_ice)
13745 if (MagicValueInt->getActiveBits() > 64) {
13746 Diag(I->getRange().getBegin(),
13747 diag::err_type_tag_for_datatype_too_large)
13751 uint64_t MagicValue = MagicValueInt->getZExtValue();
13752 RegisterTypeTagForDatatype(I->getArgumentKind(),
13754 I->getMatchingCType(),
13755 I->getLayoutCompatible(),
13756 I->getMustBeNull());
13761 auto *VD = dyn_cast<VarDecl>(DD);
13762 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13774 bool DiagnosedMultipleDecomps =
false;
13776 bool DiagnosedNonDeducedAuto =
false;
13778 for (
unsigned i = 0, e =
Group.size(); i != e; ++i) {
13782 if (
auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13783 if (!FirstDeclaratorInGroup)
13784 FirstDeclaratorInGroup = DD;
13785 if (!FirstDecompDeclaratorInGroup)
13786 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13789 FirstNonDeducedAutoInGroup = DD;
13791 if (FirstDeclaratorInGroup != DD) {
13794 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13796 diag::err_decomp_decl_not_alone)
13798 << DD->getSourceRange();
13799 DiagnosedMultipleDecomps =
true;
13805 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13807 diag::err_auto_non_deduced_not_alone)
13808 << FirstNonDeducedAutoInGroup->
getType()
13811 << DD->getSourceRange();
13812 DiagnosedNonDeducedAuto =
true;
13817 Decls.push_back(D);
13823 handleTagNumbering(Tag, S);
13824 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13830 return BuildDeclaratorGroup(Decls);
13840 if (
Group.size() > 1) {
13842 VarDecl *DeducedDecl =
nullptr;
13843 for (
unsigned i = 0, e =
Group.size(); i != e; ++i) {
13854 auto *AT = dyn_cast<AutoType>(DT);
13856 diag::err_auto_different_deductions)
13857 << (AT ? (
unsigned)AT->getKeyword() : 3) << Deduced
13870 ActOnDocumentableDecls(
Group);
13872 return DeclGroupPtrTy::make(
13877 ActOnDocumentableDecls(D);
13885 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13886 Group[0]->getLocation()) &&
13887 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13888 Group[0]->getLocation()))
13891 if (
Group.size() >= 2) {
13900 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13917 CheckExtraCXXDefaultArguments(D);
13939 << GetNameForDeclarator(D).getName();
13965 getLangOpts().
CPlusPlus17 ? diag::ext_register_storage_class
13966 : diag::warn_deprecated_register)
13974 diag::err_invalid_storage_class_in_func_decl);
13983 << getLangOpts().CPlusPlus17;
13988 DiagnoseFunctionSpecifiers(DS);
13990 CheckFunctionOrTemplateParamDeclarator(S, D);
13999 ForVisibleRedeclaration);
14007 PrevDecl =
nullptr;
14008 }
else if (S->isDeclScope(PrevDecl)) {
14030 assert(S->isFunctionPrototypeScope());
14031 assert(S->getFunctionPrototypeDepth() >= 1);
14033 S->getNextFunctionPrototypeIndex());
14038 IdResolver.AddDecl(New);
14040 ProcessDeclAttributes(S, New, D);
14047 if (New->
hasAttr<BlocksAttr>()) {
14051 if (getLangOpts().
OpenCL)
14052 deduceOpenCLAddressSpace(New);
14075 if (inTemplateInstantiation())
14081 Diag(
Parameter->getLocation(), diag::warn_unused_parameter)
14089 if (LangOpts.NumLargeByValueCopy == 0)
14096 if (Size > LangOpts.NumLargeByValueCopy)
14107 if (Size > LangOpts.NumLargeByValueCopy)
14118 if (getLangOpts().ObjCAutoRefCount &&
14132 NameLoc, diag::err_arc_array_param_no_ownership, T,
false));
14134 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14146 TSInfo, SC,
nullptr);
14152 if (
auto *LSI = getEnclosingLambda())
14153 LSI->LocalPacks.push_back(New);
14158 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14163 if (!CurContext->isRecord() &&
14164 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14165 AbstractParamType))
14174 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14187 !(getLangOpts().
OpenCL &&
14189 Diag(NameLoc, diag::err_arg_with_address_space);
14209 for (
int i = FTI.
NumParams; i != 0; ) {
14213 llvm::raw_svector_ostream(Code)
14223 const char* PrevSpec;
14232 FTI.
Params[i].
Param = ActOnParamDeclarator(S, ParamD);
14242 assert(getCurFunctionDecl() ==
nullptr &&
"Function parsing confused");
14254 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14255 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14256 ParentScope, D, TemplateParameterLists, Bases);
14259 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14260 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14262 if (!Bases.empty())
14263 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14269 Consumer.HandleInlineFunctionDefinition(D);
14284 if (isa<CXXMethodDecl>(FD))
14290 if (II->isStr(
"main") || II->isStr(
"efi_main"))
14306 if (FD->
hasAttr<OpenCLKernelAttr>())
14322 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14325 PossiblePrototype = Prev;
14342 if (
FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14359 if (TypoCorrectedFunctionDefinitions.count(Definition))
14364 if (SkipBody && !hasVisibleDefinition(Definition) &&
14366 Definition->isInlined() ||
14367 Definition->getDescribedFunctionTemplate() ||
14368 Definition->getNumTemplateParameterLists())) {
14371 if (
auto *TD = Definition->getDescribedFunctionTemplate())
14372 makeMergedDefinitionVisible(TD);
14373 makeMergedDefinitionVisible(
const_cast<FunctionDecl*
>(Definition));
14377 if (getLangOpts().
GNUMode && Definition->isInlineSpecified() &&
14378 Definition->getStorageClass() ==
SC_Extern)
14380 << FD << getLangOpts().CPlusPlus;
14384 Diag(Definition->getLocation(), diag::note_previous_definition);
14394 LSI->
Lambda = LambdaClass;
14412 for (
const auto &C : LambdaClass->
captures()) {
14413 if (C.capturesVariable()) {
14414 VarDecl *VD = C.getCapturedVar();
14417 const bool ByRef = C.getCaptureKind() ==
LCK_ByRef;
14419 true, C.getLocation(),
14420 C.isPackExpansion()
14422 I->getType(),
false);
14424 }
else if (C.capturesThis()) {
14440 PushFunctionScope();
14441 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14448 FD = FunTmpl->getTemplatedDecl();
14450 FD = cast<FunctionDecl>(D);
14455 PushExpressionEvaluationContext(
14456 FD->
isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14457 : ExprEvalContexts.back().Context);
14460 if (
const auto *
Attr = FD->
getAttr<AliasAttr>()) {
14465 if (
const auto *
Attr = FD->
getAttr<IFuncAttr>()) {
14471 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14473 Ctor->isDefaultConstructor() &&
14477 InstantiateDefaultCtorDefaultArgs(Ctor);
14485 CheckForFunctionRedefinition(FD,
nullptr, SkipBody);
14507 assert(inTemplateInstantiation() &&
14508 "There should be an active template instantiation on the stack "
14509 "when instantiating a generic lambda!");
14513 PushFunctionScope();
14530 RequireCompleteType(FD->
getLocation(), ResultType,
14531 diag::err_func_def_incomplete_result))
14535 PushDeclContext(FnBodyScope, FD);
14545 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14548 assert(!isa<ParmVarDecl>(NonParmDecl) &&
14549 "parameters should not be in newly created FD yet");
14552 if (NonParmDecl->getDeclName())
14553 PushOnScopeChains(NonParmDecl, FnBodyScope,
false);
14557 if (
auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14558 for (
auto *EI : ED->enumerators())
14559 PushOnScopeChains(EI, FnBodyScope,
false);
14566 Param->setOwningFunction(FD);
14569 if (Param->getIdentifier() && FnBodyScope) {
14570 CheckShadow(FnBodyScope, Param);
14572 PushOnScopeChains(Param, FnBodyScope);
14583 assert(!FD->
hasAttr<DLLExportAttr>());
14584 Diag(FD->
getLocation(), diag::err_attribute_dllimport_function_definition);
14590 ActOnDocumentableDecl(D);
14591 if (getCurLexicalContext()->isObjCContainer() &&
14592 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14593 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14614 for (
unsigned I = 0, E =
Scope->Returns.size(); I != E; ++I) {
14615 if (
const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14616 if (!NRVOCandidate->isNRVOVariable())
14635 Outer.Fun.hasTrailingReturnType()) {
14636 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14653 if (FD->isConstexpr())
14658 if (FD->getReturnType()->getContainedDeducedType())
14661 return Consumer.shouldSkipFunctionBody(D);
14668 FD->setHasSkippedBody();
14675 return ActOnFinishFunctionBody(D, BodyArg,
false);
14690 bool IsLambda =
false;
14694 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14696 auto IsOrNestedInEscapingBlock = [&](
const BlockDecl *BD) {
14697 if (EscapeInfo.count(BD))
14698 return EscapeInfo[BD];
14710 return EscapeInfo[BD] = R;
14715 for (
const std::pair<SourceLocation, const BlockDecl *> &
P :
14717 if (IsOrNestedInEscapingBlock(
P.second))
14718 S.
Diag(
P.first, diag::warn_implicitly_retains_self)
14723 bool IsInstantiation) {
14728 FD->
addAttr(StrictFPAttr::CreateImplicit(Context));
14733 if (getLangOpts().Coroutines && FSI->
isCoroutine())
14734 CheckCompletedCoroutineBody(FD, Body);
14758 Expr *Dummy =
nullptr;
14759 if (DeduceFunctionTypeFromReturnExpr(
14768 auto *LSI = getCurLambda();
14769 if (LSI->HasImplicitReturnType) {
14770 deduceClosureReturnType(*LSI);
14776 LSI->ReturnType.isNull() ? Context.
VoidTy : LSI->ReturnType;
14781 Proto->getExtProtoInfo()));
14801 DiagnoseSizeOfParametersAndReturnValue(FD->
parameters(),
14806 MarkVTableUsed(FD->
getLocation(), Constructor->getParent());
14808 dyn_cast<CXXDestructorDecl>(FD))
14809 MarkVTableUsed(FD->
getLocation(), Destructor->getParent());
14816 computeNRVO(Body, FSI);
14828 if (PossiblePrototype) {
14832 TypeLoc TL = TI->getTypeLoc();
14835 diag::note_declaration_not_a_prototype)
14838 FTL.getRParenLoc(),
"void")
14845 std::pair<FileID, unsigned> LocInfo =
SM.getDecomposedLoc(Loc);
14846 if (LocInfo.first.isInvalid())
14849 bool Invalid =
false;
14850 StringRef Buffer =
SM.getBufferData(LocInfo.first, &Invalid);
14854 if (LocInfo.second > Buffer.size())
14857 const char *LexStart = Buffer.data() + LocInfo.second;
14858 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14860 return StartTok.consume_front(
"const") &&
14862 StartTok.startswith(
"/*") || StartTok.startswith(
"//"));
14865 auto findBeginLoc = [&]() {
14873 if (isLocAtConst(FD->
getBeginLoc(), getSourceManager(),
14881 diag::note_static_for_internal_linkage)
14903 if (
const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14904 if (!CmpndBody->body_empty())
14905 Diag(CmpndBody->body_front()->getBeginLoc(),
14906 diag::warn_dispatch_body_ignored);
14908 if (
auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14923 if (KeyFunction && KeyFunction->
isDefined(Definition))
14924 MarkVTableUsed(Definition->getLocation(), MD->
getParent(),
true);
14933 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14934 "Function parsing confused");
14935 }
else if (
ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14936 assert(MD == getCurMethodDecl() &&
"Method parsing confused");
14939 DiagnoseSizeOfParametersAndReturnValue(MD->
parameters(),
14943 computeNRVO(Body, FSI);
14947 << MD->getSelector().getAsString();
14952 bool isDesignated =
14953 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14954 assert(isDesignated && InitMethod);
14955 (void)isDesignated;
14958 auto IFace = MD->getClassInterface();
14961 auto SuperD = IFace->getSuperClass();
14971 diag::warn_objc_designated_init_missing_super_call);
14973 diag::note_objc_designated_init_marked_here);
14981 diag::warn_objc_secondary_init_missing_init_call);
14989 PopFunctionScopeInfo(ActivePolicy, dcl);
14994 DiagnoseUnguardedAvailabilityViolations(dcl);
14997 "This should only be set for ObjC methods, which should have been "
14998 "handled in the block above.");
15005 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15006 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15010 DiagnoseInvalidJumps(Body);
15013 if (!Destructor->getParent()->isDependentType())
15014 CheckDestructor(Destructor);
15016 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15017 Destructor->getParent());
15023 if (hasUncompilableErrorOccurred() ||
15024 getDiagnostics().getSuppressAllDiagnostics()) {
15025 DiscardCleanupsInEvaluationContext();
15027 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15030 ActivePolicy = &WP;
15034 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15037 if (FD && FD->
hasAttr<NakedAttr>()) {
15041 bool RegisterVariables =
false;
15042 if (
auto *DS = dyn_cast<DeclStmt>(S)) {
15043 for (
const auto *
Decl : DS->decls()) {
15044 if (
const auto *Var = dyn_cast<VarDecl>(
Decl)) {
15045 RegisterVariables =
15046 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15047 if (!RegisterVariables)
15052 if (RegisterVariables)
15054 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15055 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15056 Diag(FD->
getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15063 assert(ExprCleanupObjects.size() ==
15064 ExprEvalContexts.back().NumCleanupObjects &&
15065 "Leftover temporaries in function");
15066 assert(!Cleanup.exprNeedsCleanups() &&
15067 "Unaccounted cleanups in function");
15068 assert(MaybeODRUseExprs.empty() &&
15069 "Leftover expressions for odr-use checking");
15075 if (!IsInstantiation)
15078 PopFunctionScopeInfo(ActivePolicy, dcl);
15082 if (hasUncompilableErrorOccurred()) {
15083 DiscardCleanupsInEvaluationContext();
15086 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15087 !LangOpts.OMPTargetTriples.empty())) ||
15088 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15089 auto ES = getEmissionStatus(FD);
15092 DeclsToCheckForDeferredDiags.insert(FD);
15107 D = TD->getTemplatedDecl();
15108 ProcessDeclAttributeList(S, D, Attrs);
15110 if (
CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15111 if (Method->isStatic())
15112 checkThisInStaticMemberFunctionAttributes(Method);
15124 Scope *BlockScope = S;
15128 Scope *ContextScope = BlockScope;
15130 ContextScope = ContextScope->
getParent();
15137 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15141 PushOnScopeChains(ExternCPrev, BlockScope,
false);
15146 if (!isa<FunctionDecl>(ExternCPrev) ||
15148 cast<FunctionDecl>(ExternCPrev)->getType(),
15150 Diag(Loc, diag::ext_use_out_of_scope_declaration)
15151 << ExternCPrev << !getLangOpts().C99;
15153 return ExternCPrev;
15159 if (II.
getName().startswith(
"__builtin_"))
15160 diag_id = diag::warn_builtin_unknown;
15162 else if (getLangOpts().
OpenCL)
15163 diag_id = diag::err_opencl_implicit_function_decl;
15164 else if (getLangOpts().
C99)
15165 diag_id = diag::ext_implicit_function_decl;
15167 diag_id = diag::warn_implicit_function_decl;
15175 if (S && !ExternCPrev &&
15179 S,
nullptr, CCC, CTK_NonError);
15182 Diag(Loc, diag_id) << &II;
15184 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15191 return ExternCPrev;
15201 assert(!
Error &&
"Error setting up implicit decl!");
15226 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15229 AddKnownFunctionAttributes(FD);
15250 bool IsNothrow =
false;
15259 if (!IsNothrow && !FD->
hasAttr<ReturnsNonNullAttr>())
15276 if (!FD->
hasAttr<AllocSizeAttr>()) {
15277 FD->
addAttr(AllocSizeAttr::CreateImplicit(
15288 if (AlignmentParam.hasValue() && !FD->
hasAttr<AllocAlignAttr>()) {
15289 FD->
addAttr(AllocAlignAttr::CreateImplicit(
15322 unsigned FormatIdx;
15325 if (!FD->
hasAttr<FormatAttr>()) {
15326 const char *fmt =
"printf";
15328 if (FormatIdx < NumParams &&
15331 FD->
addAttr(FormatAttr::CreateImplicit(Context,
15334 HasVAListArg ? 0 : FormatIdx+2,
15340 if (!FD->
hasAttr<FormatAttr>())
15341 FD->
addAttr(FormatAttr::CreateImplicit(Context,
15344 HasVAListArg ? 0 : FormatIdx+2,
15350 if (!FD->
hasAttr<CallbackAttr>() &&
15352 FD->
addAttr(CallbackAttr::CreateImplicit(
15358 if (!getLangOpts().MathErrno && !FD->
hasAttr<ConstAttr>() &&
15366 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15368 switch (BuiltinID) {
15369 case Builtin::BI__builtin_fma:
15370 case Builtin::BI__builtin_fmaf:
15371 case Builtin::BI__builtin_fmal:
15372 case Builtin::BIfma:
15373 case Builtin::BIfmaf:
15374 case Builtin::BIfmal:
15383 !FD->
hasAttr<ReturnsTwiceAttr>())
15384 FD->
addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15393 !FD->
hasAttr<CUDADeviceAttr>() && !FD->
hasAttr<CUDAHostAttr>()) {
15397 if (getLangOpts().CUDAIsDevice !=
15405 switch (BuiltinID) {
15406 case Builtin::BImemalign:
15407 case Builtin::BIaligned_alloc:
15408 if (!FD->
hasAttr<AllocAlignAttr>())
15417 switch (BuiltinID) {
15418 case Builtin::BIcalloc:
15419 FD->
addAttr(AllocSizeAttr::CreateImplicit(
15422 case Builtin::BImemalign:
15423 case Builtin::BIaligned_alloc:
15424 case Builtin::BIrealloc:
15428 case Builtin::BImalloc:
15437 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15442 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15445 if (!FPT || FPT->getExceptionSpecType() ==
EST_None)
15462 if (Name->isStr(
"asprintf") || Name->isStr(
"vasprintf")) {
15465 if (!FD->
hasAttr<FormatAttr>())
15466 FD->
addAttr(FormatAttr::CreateImplicit(Context,
15468 Name->isStr(
"vasprintf") ? 0 : 3,
15472 if (Name->isStr(
"__CFStringMakeConstantString")) {
15475 if (!FD->
hasAttr<FormatArgAttr>())
15483 assert(D.
getIdentifier() &&
"Wrong callback for declspec without declarator");
15484 assert(!T.
isNull() &&
"GetTypeForDeclarator() returned null type");
15487 assert(D.
isInvalidType() &&
"no declarator info for valid type");
15503 if (CurContext->isFunctionOrMethod())
15526 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15548 if (BT->isInteger())
15554 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15560 QualType EnumUnderlyingTy,
bool IsFixed,
15562 if (IsScoped != Prev->
isScoped()) {
15563 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15569 if (IsFixed && Prev->
isFixed()) {
15575 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15581 }
else if (IsFixed != Prev->
isFixed()) {
15582 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15601 default: llvm_unreachable(
"Invalid tag kind for redecl diagnostic!");
15616 if (isa<TypedefDecl>(PrevDecl))
15617 return NTK_Typedef;
15618 else if (isa<TypeAliasDecl>(PrevDecl))
15619 return NTK_TypeAlias;
15620 else if (isa<ClassTemplateDecl>(PrevDecl))
15621 return NTK_Template;
15622 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15623 return NTK_TypeAliasTemplate;
15624 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15625 return NTK_TemplateTemplateArgument;
15630 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15632 return NTK_NonUnion;
15634 return NTK_NonEnum;
15636 llvm_unreachable(
"invalid TTK");
15661 if (OldTag != NewTag &&
15676 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15679 if (IsIgnoredLoc(NewTagLoc))
15682 auto IsIgnored = [&](
const TagDecl *Tag) {
15683 return IsIgnoredLoc(Tag->getLocation());
15694 isTemplate = Record->getDescribedClassTemplate();
15696 if (inTemplateInstantiation()) {
15697 if (OldTag != NewTag) {
15700 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15708 if (isDefinition) {
15716 bool previousMismatch =
false;
15718 if (I->getTagKind() != NewTag) {
15723 if (!previousMismatch) {
15724 previousMismatch =
true;
15725 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15729 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15742 if (PrevDef && IsIgnored(PrevDef))
15746 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15753 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15783 if (!Namespace || Namespace->isAnonymousNamespace())
15786 Namespaces.push_back(II);
15789 if (Lookup == Namespace)
15796 llvm::raw_svector_ostream OS(Insertion);
15799 std::reverse(Namespaces.begin(), Namespaces.end());
15800 for (
auto *II : Namespaces)
15801 OS << II->getName() <<
"::";
15814 if (OldDC->
Equals(NewDC))
15842 bool &OwnedDecl,
bool &IsDependent,
15844 bool ScopedEnumUsesClassTag,
TypeResult UnderlyingType,
15845 bool IsTypeSpecifier,
bool IsTemplateParamOrArg,
15849 assert((Name !=
nullptr || TUK == TUK_Definition) &&
15850 "Nameless record must be a definition!");
15851 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15855 bool ScopedEnum = ScopedEnumKWLoc.
isValid();
15858 bool isMemberSpecialization =
false;
15859 bool Invalid =
false;
15864 if (TemplateParameterLists.size() > 0 ||
15865 (SS.
isNotEmpty() && TUK != TUK_Reference)) {
15867 MatchTemplateParametersToScopeSpecifier(
15868 KWLoc, NameLoc, SS,
nullptr, TemplateParameterLists,
15869 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15871 Diag(KWLoc, diag::err_enum_template);
15875 if (TemplateParams->size() > 0) {
15884 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15885 AS, ModulePrivateLoc,
15887 TemplateParameterLists.data(), SkipBody);
15888 return Result.get();
15891 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15893 isMemberSpecialization =
true;
15897 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15898 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15905 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15906 bool IsFixed = !UnderlyingType.
isUnset() || ScopedEnum;
15909 if (UnderlyingType.
isInvalid() || (!UnderlyingType.
get() && ScopedEnum)) {
15913 }
else if (UnderlyingType.
get()) {
15917 GetTypeFromParser(UnderlyingType.
get(), &TI);
15918 EnumUnderlying = TI;
15920 if (CheckEnumUnderlyingType(TI))
15925 UPPC_FixedUnderlyingType))
15933 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15940 bool isStdBadAlloc =
false;
15941 bool isStdAlignValT =
false;
15944 if (TUK == TUK_Friend || TUK == TUK_Reference)
15945 Redecl = NotForRedeclaration;
15950 auto createTagFromNewDecl = [&]() ->
TagDecl * {
15951 assert(!getLangOpts().
CPlusPlus &&
"not meant for C++ usage");
15960 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15962 if (TUK != TUK_Definition && !Invalid)
15964 if (EnumUnderlying) {
15965 EnumDecl *ED = cast<EnumDecl>(New);
15977 if (
RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15987 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->
ShouldSkip)) {
15988 AddAlignmentAttributesForRecord(RD);
15989 AddMsStructLayoutForRecord(RD);
16003 goto CreateNewDecl;
16008 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16009 DC = computeDeclContext(SS,
false);
16011 IsDependent =
true;
16015 DC = computeDeclContext(SS,
true);
16023 if (RequireCompleteDeclContext(SS, DC))
16028 LookupQualifiedName(
Previous, DC);
16040 if (
Previous.wasNotFoundInCurrentInstantiation() &&
16041 (TUK == TUK_Reference || TUK == TUK_Friend)) {
16042 IsDependent =
true;
16047 Diag(NameLoc, diag::err_not_tag_in_scope)
16051 goto CreateNewDecl;
16058 if (TUK != TUK_Reference && TUK != TUK_Friend &&
16072 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16096 if (!
Previous.empty() && TUK == TUK_Friend) {
16099 bool FriendSawTagOutsideEnclosingNamespace =
false;
16105 if (getLangOpts().MSVCCompat)
16106 FriendSawTagOutsideEnclosingNamespace =
true;
16115 if (
Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16117 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16126 if (!getLangOpts().
CPlusPlus && TUK != TUK_Reference) {
16131 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
16137 Previous.getFoundDecl()->isTemplateParameter()) {
16139 DiagnoseTemplateParameterShadow(NameLoc,
Previous.getFoundDecl());
16144 if (getLangOpts().
CPlusPlus && Name && DC && StdNamespace &&
16145 DC->
Equals(getStdNamespace())) {
16146 if (Name->isStr(
"bad_alloc")) {
16148 isStdBadAlloc =
true;
16153 if (
Previous.empty() && StdBadAlloc)
16154 Previous.addDecl(getStdBadAlloc());
16155 }
else if (Name->isStr(
"align_val_t")) {
16156 isStdAlignValT =
true;
16157 if (
Previous.empty() && StdAlignValT)
16158 Previous.addDecl(getStdAlignValT());
16167 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16168 if (Invalid)
goto CreateNewDecl;
16171 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16205 assert(TUK == TUK_Friend);
16222 Previous.setRedeclarationKind(forRedeclarationInCurContext());
16223 LookupQualifiedName(
Previous, SearchDC);
16225 Previous.setRedeclarationKind(forRedeclarationInCurContext());
16249 TagDecl *Tag = TT->getDecl();
16252 ->
Equals(TD->getDeclContext()->getRedeclContext())) {
16265 if (
auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16266 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16267 if (SS.
isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16268 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16270 *
this, OldTag->getDeclContext(), SearchDC))) {
16271 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16272 Diag(Shadow->getTargetDecl()->getLocation(),
16273 diag::note_using_decl_target);
16274 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16278 goto CreateNewDecl;
16282 if (
TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16286 if (TUK == TUK_Reference || TUK == TUK_Friend ||
16287 isDeclInScope(DirectPrevDecl, SearchDC, S,
16288 SS.
isNotEmpty() || isMemberSpecialization)) {
16291 if (!isAcceptableTagRedeclaration(PrevTagDecl,
Kind,
16292 TUK == TUK_Definition, KWLoc,
16294 bool SafeToContinue
16295 = (PrevTagDecl->getTagKind() !=
TTK_Enum &&
16297 if (SafeToContinue)
16298 Diag(KWLoc, diag::err_use_with_wrong_tag)
16301 PrevTagDecl->getKindName());
16303 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16304 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16306 if (SafeToContinue)
16307 Kind = PrevTagDecl->getTagKind();
16317 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16318 if (TUK == TUK_Reference || TUK == TUK_Friend)
16319 return PrevTagDecl;
16323 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16324 else if (
const Type *T = EnumUnderlying.dyn_cast<
const Type*>())
16325 EnumUnderlyingTy =
QualType(T, 0);
16330 if (CheckEnumRedeclaration(NameLoc.
isValid() ? NameLoc : KWLoc,
16331 ScopedEnum, EnumUnderlyingTy,
16332 IsFixed, PrevEnum))
16333 return TUK == TUK_Declaration ? PrevTagDecl :
nullptr;
16341 S->isDeclScope(PrevDecl)) {
16342 Diag(NameLoc, diag::ext_member_redeclared);
16343 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16349 if (TUK == TUK_Reference || TUK == TUK_Friend) {
16350 if (!Attrs.
empty()) {
16353 }
else if (TUK == TUK_Reference &&
16354 (PrevTagDecl->getFriendObjectKind() ==
16367 return PrevTagDecl;
16372 return PrevTagDecl;
16377 if (TUK == TUK_Definition) {
16378 if (
NamedDecl *Def = PrevTagDecl->getDefinition()) {
16382 bool IsExplicitSpecializationAfterInstantiation =
false;
16383 if (isMemberSpecialization) {
16385 IsExplicitSpecializationAfterInstantiation =
16386 RD->getTemplateSpecializationKind() !=
16388 else if (
EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16389 IsExplicitSpecializationAfterInstantiation =
16390 ED->getTemplateSpecializationKind() !=
16399 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16410 SkipBody->
New = createTagFromNewDecl();
16416 makeMergedDefinitionVisible(Hidden);
16420 }
else if (!IsExplicitSpecializationAfterInstantiation) {
16423 if (!getLangOpts().
CPlusPlus && S->containedInPrototypeScope())
16424 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16426 Diag(NameLoc, diag::err_redefinition) << Name;
16427 notePreviousDefinition(Def,
16428 NameLoc.
isValid() ? NameLoc : KWLoc);
16440 if (TD->isBeingDefined()) {
16441 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16442 Diag(PrevTagDecl->getLocation(),
16443 diag::note_previous_definition);
16457 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16458 SearchDC = PrevTagDecl->getDeclContext();
16483 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16486 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16492 }
else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16493 SS.
isNotEmpty() || isMemberSpecialization)) {
16497 }
else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16499 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16505 }
else if (
TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16507 if (isa<TypeAliasDecl>(PrevDecl))
Kind = 1;
16508 Diag(NameLoc, diag::err_tag_definition_of_typedef)
16509 << Name <<
Kind << TND->getUnderlyingType();
16517 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16518 notePreviousDefinition(PrevDecl, NameLoc);
16533 PrevDecl = cast<TagDecl>(
Previous.getFoundDecl());
16549 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16550 ScopedEnumUsesClassTag, IsFixed);
16552 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16553 StdAlignValT = cast<EnumDecl>(New);
16556 if (TUK != TUK_Definition && !Invalid) {
16558 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16562 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->
getDefinition())) {
16563 Diag(Loc, diag::ext_forward_ref_enum_def)
16567 unsigned DiagID = diag::ext_forward_ref_enum;
16568 if (getLangOpts().MSVCCompat)
16569 DiagID = diag::ext_ms_forward_ref_enum;
16571 DiagID = diag::err_forward_ref_enum;
16576 if (EnumUnderlying) {
16577 EnumDecl *ED = cast<EnumDecl>(New);
16583 assert(ED->
isComplete() &&
"enum with type should be complete");
16593 cast_or_null<CXXRecordDecl>(PrevDecl));
16595 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16596 StdBadAlloc = cast<CXXRecordDecl>(New);
16599 cast_or_null<RecordDecl>(PrevDecl));
16604 if (getLangOpts().
CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16605 TUK == TUK_Definition) {
16611 if (!Invalid && getLangOpts().
CPlusPlus && TUK == TUK_Definition &&
16623 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16624 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16625 isMemberSpecialization))
16629 if (TemplateParameterLists.size() > 0) {
16637 if (
RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16647 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->
ShouldSkip)) {
16648 AddAlignmentAttributesForRecord(RD);
16649 AddMsStructLayoutForRecord(RD);
16653 if (ModulePrivateLoc.
isValid()) {
16654 if (isMemberSpecialization)
16667 if (isMemberSpecialization && CheckMemberSpecialization(New,
Previous))
16674 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16678 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16679 Diag(Loc, diag::err_type_defined_in_param_type)
16683 }
else if (!PrevDecl) {
16699 if (TUK == TUK_Friend)
16703 if (!Invalid && SearchDC->
isRecord())
16704 SetMemberAccessSpecifier(New, PrevDecl, AS);
16707 CheckRedeclarationInModule(New, PrevDecl);
16709 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->
ShouldSkip))
16712 ProcessDeclAttributeList(S, New, Attrs);
16713 AddPragmaAttributes(S, New);
16716 if (TUK == TUK_Friend) {
16725 if (
Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16726 PushOnScopeChains(New, EnclosingScope,
false);
16728 S = getNonFieldDeclScope(S);
16729 PushOnScopeChains(New, S,
true);
16731 CurContext->addDecl(New);
16742 mergeDeclAttributes(New, PrevDecl);
16744 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16745 inferGslOwnerPointerAttribute(CXXRD);
16749 AddPushedVisibilityAttribute(New);
16752 CompleteMemberSpecialization(New,
Previous);
16757 if (Invalid && getLangOpts().
CPlusPlus) {
16759 if (
auto RD = dyn_cast<RecordDecl>(New))
16762 }
else if (SkipBody && SkipBody->
ShouldSkip) {
16770 AdjustDeclIfTemplate(TagD);
16771 TagDecl *Tag = cast<TagDecl>(TagD);
16774 PushDeclContext(S, Tag);
16776 ActOnDocumentableDecl(TagD);
16780 AddPushedVisibilityAttribute(Tag);
16785 if (!hasStructuralCompatLayout(Prev, SkipBody.
New))
16789 makeMergedDefinitionVisible(SkipBody.
Previous);
16794 assert(isa<ObjCContainerDecl>(IDecl) &&
16795 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16798 "The next DeclContext should be lexically contained in the current one.");
16805 bool IsFinalSpelledSealed,
16808 AdjustDeclIfTemplate(TagD);
16811 FieldCollector->StartClass();
16820 Record->
addAttr(FinalAttr::Create(
16822 static_cast<FinalAttr::Spelling
>(IsFinalSpelledSealed)));
16839 PushOnScopeChains(InjectedClassName, S);
16841 "Broken injected-class-name");
16846 AdjustDeclIfTemplate(TagD);
16847 TagDecl *Tag = cast<TagDecl>(TagD);
16852 assert(Tag->
isInvalidDecl() &&
"We should already have completed it");
16853 if (
RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16857 if (
auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16858 FieldCollector->FinishClass();
16859 if (RD->
hasAttr<SYCLSpecialClassAttr>() && getLangOpts().SYCLIsDevice) {
16861 assert(Def &&
"The record is expected to have a completed definition");
16862 unsigned NumInitMethods = 0;
16863 for (
auto *Method : Def->methods()) {
16864 if (!Method->getIdentifier())
16866 if (Method->getName() ==
"__init")
16869 if (NumInitMethods > 1 || !Def->hasInitMethod())
16870 Diag(RD->
getLocation(), diag::err_sycl_special_type_num_init_method);
16877 if (getCurLexicalContext()->isObjCContainer() &&
16883 Consumer.HandleTagDeclDefinition(Tag);
16888 AlignPackStack.hasValue()) {
16893 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16897 if (llvm::any_of(RD->
fields(),
16898 [](
const FieldDecl *FD) { return FD->isBitField(); }))
16899 Diag(BraceRange.
getBegin(), diag::warn_pragma_align_not_xl_compatible);
16909 assert(DC == CurContext &&
"Mismatch of container contexts");
16910 OriginalLexicalContext = DC;
16911 ActOnObjCContainerFinishDefinition();
16915 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16916 OriginalLexicalContext =
nullptr;
16920 AdjustDeclIfTemplate(TagD);
16921 TagDecl *Tag = cast<TagDecl>(TagD);
16926 if (
RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16940 QualType FieldTy,
bool IsMsStruct,
16941 Expr *BitWidth,
bool *ZeroWidth) {
16954 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16955 diag::err_field_incomplete_or_sizeless))
16958 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16960 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16962 }
else if (DiagnoseUnexpandedParameterPack(
const_cast<Expr *
>(BitWidth),
16963 UPPC_BitFieldWidth))
16972 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &
Value, AllowFold);
16975 BitWidth = ICE.
get();
16977 if (
Value != 0 && ZeroWidth)
16978 *ZeroWidth =
false;
16981 if (
Value == 0 && FieldName)
16982 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16984 if (
Value.isSigned() &&
Value.isNegative()) {
16986 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16988 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16995 return Diag(FieldLoc, diag::err_bitfield_too_wide)
17000 uint64_t TypeStorageSize = Context.
getTypeSize(FieldTy);
17001 uint64_t TypeWidth = Context.
getIntWidth(FieldTy);
17002 bool BitfieldIsOverwide =
Value.ugt(TypeWidth);
17006 bool CStdConstraintViolation =
17007 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17008 bool MSBitfieldViolation =
17009 Value.ugt(TypeStorageSize) &&
17011 if (CStdConstraintViolation || MSBitfieldViolation) {
17012 unsigned DiagWidth =
17013 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17014 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17016 << !CStdConstraintViolation << DiagWidth;
17022 if (BitfieldIsOverwide && !FieldTy->
isBooleanType() && FieldName) {
17023 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17036 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17037 DeclStart, D,
static_cast<Expr*
>(BitfieldWidth),
17063 CheckExtraCXXDefaultArguments(D);
17066 UPPC_DataMemberType)) {
17077 << getLangOpts().CPlusPlus17;
17080 diag::err_invalid_thread)
17086 ForVisibleRedeclaration);
17088 switch (
Previous.getResultKind()) {
17095 PrevDecl =
Previous.getRepresentativeDecl();
17109 PrevDecl =
nullptr;
17112 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17113 PrevDecl =
nullptr;
17119 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17120 TSSL, AS, PrevDecl, &D);
17132 PushOnScopeChains(NewFD, S);
17152 bool Mutable,
Expr *BitWidth,
17158 bool InvalidDecl =
false;
17164 InvalidDecl =
true;
17170 if (RequireCompleteSizedType(Loc, EltTy,
17171 diag::err_field_incomplete_or_sizeless)) {
17174 InvalidDecl =
true;
17180 InvalidDecl =
true;
17188 Diag(Loc, diag::err_field_with_address_space);
17190 InvalidDecl =
true;
17193 if (LangOpts.OpenCL) {
17198 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17200 InvalidDecl =
true;
17204 if (BitWidth && !getOpenCLOptions().isAvailableOption(
17205 "__cl_clang_bitfields", LangOpts)) {
17206 Diag(Loc, diag::err_opencl_bitfields);
17207 InvalidDecl =
true;
17212 if (!InvalidDecl && getLangOpts().
CPlusPlus && !II && BitWidth &&
17214 InvalidDecl =
true;
17215 Diag(Loc, diag::err_anon_bitfield_qualifiers);
17221 if (!tryToFixVariablyModifiedVarType(
17222 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17223 InvalidDecl =
true;
17227 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17228 diag::err_abstract_type_in_decl,
17229 AbstractFieldType))
17230 InvalidDecl =
true;
17232 bool ZeroWidth =
false;
17234 BitWidth =
nullptr;
17237 BitWidth = VerifyBitField(Loc, II, T, Record->
isMsStruct(Context), BitWidth,
17240 InvalidDecl =
true;
17241 BitWidth =
nullptr;
17247 if (!InvalidDecl && Mutable) {
17248 unsigned DiagID = 0;
17250 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17251 : diag::err_mutable_reference;
17253 DiagID = diag::err_mutable_const;
17259 Diag(ErrLoc, DiagID);
17260 if (DiagID != diag::ext_mutable_reference) {
17262 InvalidDecl =
true;
17274 BitWidth, Mutable, InitStyle);
17278 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17279 Diag(Loc, diag::err_duplicate_member) << II;
17284 if (!InvalidDecl && getLangOpts().
CPlusPlus) {
17294 if (CheckNontrivialField(NewFD))
17304 diag::ext_union_member_of_reference_type :
17305 diag::err_union_member_of_reference_type)
17307 if (!getLangOpts().MicrosoftExt)
17317 ProcessDeclAttributes(getCurScope(), NewFD, *D);
17320 CheckAlignasUnderalignment(NewFD);
17325 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17329 Diag(Loc, diag::warn_attribute_weak_on_field);
17342 assert(getLangOpts().
CPlusPlus &&
"valid check only for C++");
17362 member = CXXCopyConstructor;
17364 member = CXXDefaultConstructor;
17366 member = CXXCopyAssignment;
17370 if (
member != CXXInvalid) {
17379 if (getSourceManager().isInSystemHeader(Loc)) {
17380 if (!FD->
hasAttr<UnavailableAttr>())
17381 FD->
addAttr(UnavailableAttr::CreateImplicit(Context,
"",
17382 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17388 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17389 diag::err_illegal_union_or_anon_struct_member)
17391 DiagnoseNontrivial(RDecl,
member);
17392 return !getLangOpts().CPlusPlus11;
17404 switch (ivarVisibility) {
17405 default: llvm_unreachable(
"Unknown visitibility kind");
17421 Expr *BitWidth = (
Expr*)BitfieldWidth;
17433 BitWidth = VerifyBitField(Loc, II, T,
false, BitWidth).get();
17443 Diag(Loc, diag::err_ivar_reference_type);
17449 if (!tryToFixVariablyModifiedVarType(
17450 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17464 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17465 if (LangOpts.ObjCRuntime.isFragile()) {
17467 EnclosingContext = IMPDecl->getClassInterface();
17468 assert(EnclosingContext &&
"Implementation has no class interface!");
17471 EnclosingContext = EnclosingDecl;
17474 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17475 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17476 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17480 EnclosingContext = EnclosingDecl;
17485 DeclStart, Loc, II, T,
17486 TInfo, ac, (
Expr *)BitfieldWidth);
17489 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17490 ForVisibleRedeclaration);
17491 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17492 && !isa<TagDecl>(PrevDecl)) {
17493 Diag(Loc, diag::err_duplicate_member) << II;
17500 ProcessDeclAttributes(S, NewID, D);
17506 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17516 IdResolver.AddDecl(NewID);
17519 if (LangOpts.ObjCRuntime.isNonFragile() &&
17520 !NewID->
isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17521 Diag(Loc, diag::warn_ivars_in_interface);
17532 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17535 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17543 if (!CD->IsClassExtension())
17555 DeclLoc, DeclLoc,
nullptr,
17561 AllIvarDecls.push_back(Ivar);
17568 assert(EnclosingDecl &&
"missing record or interface decl");
17573 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17577 case Decl::ObjCCategory:
17578 Context.
ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17580 case Decl::ObjCImplementation:
17582 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17587 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17588 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17592 unsigned NumNamedMembers = 0;
17594 for (
const auto *I : Record->
decls()) {
17595 if (
const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17596 if (IFD->getDeclName())
17613 RecFields.push_back(FD);
17633 bool IsLastField = (i + 1 == Fields.end());
17642 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17648 unsigned DiagID = 0;
17649 if (!Record->
isUnion() && !IsLastField) {
17652 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17656 }
else if (Record->
isUnion())
17657 DiagID = getLangOpts().MicrosoftExt
17658 ? diag::ext_flexible_array_union_ms
17659 : getLangOpts().CPlusPlus
17660 ? diag::ext_flexible_array_union_gnu
17661 : diag::err_flexible_array_union;
17662 else if (NumNamedMembers < 1)
17663 DiagID = getLangOpts().MicrosoftExt
17664 ? diag::ext_flexible_array_empty_aggregate_ms
17665 : getLangOpts().CPlusPlus
17666 ? diag::ext_flexible_array_empty_aggregate_gnu
17667 : diag::err_flexible_array_empty_aggregate;
17677 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17680 if (!getLangOpts().
C99)
17691 Diag(FD->
getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17705 RequireCompleteSizedType(
17707 diag::err_field_incomplete_or_sizeless)) {
17732 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17734 diag::err_abstract_type_in_decl,
17735 AbstractIvarType)) {
17749 }
else if (Record && Record->
isUnion() &&
17751 getSourceManager().isInSystemHeader(FD->
getLocation()) &&
17761 FD->
addAttr(UnavailableAttr::CreateImplicit(
17762 Context,
"", UnavailableAttr::IR_ARCFieldWithOwnership,
17764 }
else if (getLangOpts().ObjC &&
17781 if (Record && !getLangOpts().
CPlusPlus &&
17782 !shouldIgnoreForRecordTriviality(FD)) {
17804 if (RT->getDecl()->getArgPassingRestrictions() ==
17820 bool Completed =
false;
17822 if (!CXXRecord->isInvalidDecl()) {
17825 I = CXXRecord->conversion_begin(),
17826 E = CXXRecord->conversion_end(); I != E; ++I)
17827 I.setAccess((*I)->getAccess());
17831 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17833 if (!CXXRecord->isDependentType()) {
17834 if (!CXXRecord->isInvalidDecl()) {
17838 if (CXXRecord->getNumVBases()) {
17840 CXXRecord->getFinalOverriders(FinalOverriders);
17842 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17843 MEnd = FinalOverriders.end();
17846 SOEnd = M->second.end();
17847 SO != SOEnd; ++SO) {
17848 assert(SO->second.size() > 0 &&
17849 "Virtual function without overriding functions?");
17850 if (SO->second.size() == 1)
17858 << (
const NamedDecl *)M->first << Record;
17859 Diag(M->first->getLocation(),
17860 diag::note_overridden_virtual_function);
17862 OM = SO->second.begin(),
17863 OMEnd = SO->second.end();
17865 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17866 << (
const NamedDecl *)M->first << OM->Method->getParent();
17871 CXXRecord->completeDefinition(&FinalOverriders);
17882 ProcessDeclAttributeList(S, Record, Attrs);
17886 auto *Dtor = CXXRecord->getDestructor();
17887 if (Dtor && Dtor->isImplicit() &&
17888 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17889 CXXRecord->setImplicitDestructorIsDeleted();
17890 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17895 CheckAlignasUnderalignment(Record);
17897 if (
const MSInheritanceAttr *IA = Record->
getAttr<MSInheritanceAttr>())
17898 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17899 IA->getRange(), IA->getBestCase(),
17900 IA->getInheritanceModel());
17906 bool CheckForZeroSize;
17908 CheckForZeroSize =
true;
17913 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17914 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17915 CXXRecord->isCLike();
17917 if (CheckForZeroSize) {
17918 bool ZeroSize =
true;
17919 bool IsEmpty =
true;
17920 unsigned NonBitFields = 0;
17923 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17925 if (I->isUnnamedBitfield()) {
17926 if (!I->isZeroLengthBitField(Context))
17930 QualType FieldType = I->getType();
17942 diag::warn_zero_size_struct_union_in_extern_c :
17943 diag::warn_zero_size_struct_union_compat)
17944 << IsEmpty << Record->
isUnion() << (NonBitFields > 1);
17949 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17950 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17951 diag::ext_no_named_members_in_struct_union)
17959 ID->setEndOfDefinitionLoc(RBrac);
17961 for (
unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17963 ID->addDecl(ClsFields[i]);
17967 if (
ID->getSuperClass())
17968 DiagnoseDuplicateIvars(
ID,
ID->getSuperClass());
17970 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17971 assert(IMPDecl &&
"ActOnFields - missing ObjCImplementationDecl");
17972 for (
unsigned I = 0, N = RecFields.size(); I != N; ++I)
17976 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17977 IMPDecl->setIvarLBraceLoc(LBrac);
17978 IMPDecl->setIvarRBraceLoc(RBrac);
17980 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17988 for (
unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17992 Diag(ClsFields[i]->getLocation(),
17993 diag::err_duplicate_ivar_declaration);
17994 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18000 Diag(ClsFields[i]->getLocation(),
18001 diag::err_duplicate_ivar_declaration);
18002 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18008 CDecl->addDecl(ClsFields[i]);
18010 CDecl->setIvarLBraceLoc(LBrac);
18011 CDecl->setIvarRBraceLoc(RBrac);
18022 "Integral type required!");
18025 if (
Value.isUnsigned() ||
Value.isNonNegative()) {
18028 return Value.getActiveBits() <= BitWidth;
18030 return Value.getMinSignedBits() <= BitWidth;
18040 const unsigned NumTypes = 4;
18041 QualType SignedIntegralTypes[NumTypes] = {
18044 QualType UnsignedIntegralTypes[NumTypes] = {
18051 : UnsignedIntegralTypes;
18052 for (
unsigned I = 0; I != NumTypes; ++I)
18068 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18072 Val = DefaultLvalueConversion(Val).get();
18081 if (getLangOpts().
CPlusPlus11 && Enum->isFixed()) {
18085 EltTy = Enum->getIntegerType();
18092 Val = Converted.
get();
18095 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18099 if (Enum->isComplete()) {
18100 EltTy = Enum->getIntegerType();
18109 .isWindowsMSVCEnvironment()) {
18110 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18112 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18117 Val = ImpCastExprToType(Val, EltTy,
18136 Diag(IdLoc, diag::ext_enum_value_not_int)
18138 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18141 Val = ImpCastExprToType(Val, Context.
IntTy, CK_IntegralCast).get();
18150 if (Enum->isDependentType())
18152 else if (!LastEnumConst) {
18161 if (Enum->isFixed()) {
18162 EltTy = Enum->getIntegerType();
18165 EltTy = Context.
IntTy;
18171 EltTy = LastEnumConst->
getType();
18174 if (EnumVal < LastEnumConst->getInitVal()) {
18186 if (T.
isNull() || Enum->isFixed()) {
18190 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18192 if (Enum->isFixed())
18194 Diag(IdLoc, diag::err_enumerator_wrapped)
18198 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18209 EnumVal = EnumVal.zextOrTrunc(Context.
getIntWidth(EltTy));
18218 Diag(IdLoc, diag::warn_enum_value_overflow);
18222 Diag(IdLoc, diag::ext_enum_value_not_int)
18231 EnumVal = EnumVal.extOrTrunc(Context.
getIntWidth(EltTy));
18241 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18248 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18249 forRedeclarationInCurContext());
18250 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18254 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18256 if (!PrevED->
getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18269 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18271 cast_or_null<EnumConstantDecl>(lastEnumConst);
18275 S = getNonFieldDeclScope(S);
18279 LookupResult R(*
this,
Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18285 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18287 PrevDecl =
nullptr;
18300 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc,
Id, Val);
18305 if (!TheEnumDecl->
isScoped() && isa<ValueDecl>(PrevDecl)) {
18307 CheckShadow(New, PrevDecl, R);
18312 assert((getLangOpts().
CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18313 "Received TagDecl when not in C++!");
18314 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18315 if (isa<EnumConstantDecl>(PrevDecl))
18316 Diag(IdLoc, diag::err_redefinition_of_enumerator) <<
Id;
18318 Diag(IdLoc, diag::err_redefinition) <<
Id;
18319 notePreviousDefinition(PrevDecl, IdLoc);
18325 ProcessDeclAttributeList(S, New, Attrs);
18326 AddPragmaAttributes(S, New);
18330 PushOnScopeChains(New, S);
18332 ActOnDocumentableDecl(New);
18350 if (!BO->isAdditiveOp())
18358 InitExpr = BO->getLHS();
18362 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18382 if (!Enum->getIdentifier())
18386 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18389 if (S.
Diags.
isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18395 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18398 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18403 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18406 DuplicatesVector DupVector;
18407 ValueToVectorMap EnumMap;
18411 for (
auto *Element : Elements) {
18425 EnumMap.insert({EnumConstantToKey(ECD), ECD});
18428 if (EnumMap.size() == 0)
18432 for (
auto *Element : Elements) {
18438 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18439 if (Iter == EnumMap.end())
18442 DeclOrVector& Entry = Iter->second;
18449 auto Vec = std::make_unique<ECDVector>();
18451 Vec->push_back(ECD);
18458 DupVector.emplace_back(std::move(Vec));
18462 ECDVector *Vec = Entry.get<ECDVector*>();
18464 if (*Vec->begin() == ECD)
18467 Vec->push_back(ECD);
18471 for (
const auto &Vec : DupVector) {
18472 assert(Vec->size() > 1 &&
"ECDVector should have at least 2 elements.");
18475 auto *FirstECD = Vec->front();
18476 S.
Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18477 << FirstECD <<
toString(FirstECD->getInitVal(), 10)
18478 << FirstECD->getSourceRange();
18482 for (
auto *ECD : llvm::drop_begin(*Vec))
18483 S.
Diag(ECD->getLocation(), diag::note_duplicate_element)
18484 << ECD <<
toString(ECD->getInitVal(), 10)
18485 << ECD->getSourceRange();
18490 bool AllowMask)
const {
18491 assert(ED->
isClosedFlag() &&
"looking for value in non-flag or open enum");
18494 auto R = FlagBitsCache.insert(std::make_pair(ED,
llvm::APInt()));
18499 const auto &EVal = E->getInitVal();
18501 if (EVal.isPowerOf2())
18502 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18514 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18515 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18521 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18524 ProcessDeclAttributeList(S, Enum, Attrs);
18526 if (Enum->isDependentType()) {
18527 for (
unsigned i = 0, e = Elements.size(); i != e; ++i) {
18529 cast_or_null<EnumConstantDecl>(Elements[i]);
18530 if (!ECD)
continue;
18548 unsigned NumNegativeBits = 0;
18549 unsigned NumPositiveBits = 0;
18551 for (
unsigned i = 0, e = Elements.size(); i != e; ++i) {
18553 cast_or_null<EnumConstantDecl>(Elements[i]);
18554 if (!ECD)
continue;
18559 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18560 NumPositiveBits =
std::max(NumPositiveBits,
18561 (
unsigned)InitVal.getActiveBits());
18563 NumNegativeBits =
std::max(NumNegativeBits,
18564 (
unsigned)InitVal.getMinSignedBits());
18569 unsigned BestWidth;
18582 bool Packed = Enum->hasAttr<PackedAttr>();
18585 if (LangOpts.ShortEnums)
18590 if (Enum->isComplete()) {
18591 BestType = Enum->getIntegerType();
18595 BestPromotionType = BestType;
18599 else if (NumNegativeBits) {
18603 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18605 BestWidth = CharWidth;
18606 }
else if (Packed && NumNegativeBits <= ShortWidth &&
18607 NumPositiveBits < ShortWidth) {
18609 BestWidth = ShortWidth;
18610 }
else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18611 BestType = Context.
IntTy;
18612 BestWidth = IntWidth;
18616 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18617 BestType = Context.
LongTy;
18621 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18622 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18626 BestPromotionType = (BestWidth <= IntWidth ? Context.
IntTy : BestType);
18631 if (Packed && NumPositiveBits <= CharWidth) {
18633 BestPromotionType = Context.
IntTy;
18634 BestWidth = CharWidth;
18635 }
else if (Packed && NumPositiveBits <= ShortWidth) {
18637 BestPromotionType = Context.
IntTy;
18638 BestWidth = ShortWidth;
18639 }
else if (NumPositiveBits <= IntWidth) {
18641 BestWidth = IntWidth;
18643 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18645 }
else if (NumPositiveBits <=
18649 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18653 assert(NumPositiveBits <= BestWidth &&
18654 "How could an initializer get larger than ULL?");
18657 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18664 for (
auto *D : Elements) {
18665 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18666 if (!ECD)
continue;
18683 !Enum->isFixed() &&
18685 NewTy = Context.
IntTy;
18686 NewWidth = IntWidth;
18688 }
else if (ECD->getType() == BestType) {
18698 NewWidth = BestWidth;
18703 InitVal = InitVal.extOrTrunc(NewWidth);
18704 InitVal.setIsSigned(NewSign);
18705 ECD->setInitVal(InitVal);
18708 if (ECD->getInitExpr() &&
18709 !Context.
hasSameType(NewTy, ECD->getInitExpr()->getType()))
18711 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18719 ECD->setType(NewTy);
18722 Enum->completeDefinition(BestType, BestPromotionType,
18723 NumPositiveBits, NumNegativeBits);
18727 if (Enum->isClosedFlag()) {
18728 for (
Decl *D : Elements) {
18730 if (!ECD)
continue;
18733 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18734 !IsValueInFlagEnum(Enum, InitVal,
true))
18741 if (Enum->hasAttrs())
18742 CheckAlignasUnderalignment(Enum);
18751 AsmString, StartLoc,
18753 CurContext->addDecl(New);
18762 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18763 LookupOrdinaryName);
18766 AsmLabelAttr *
Attr = AsmLabelAttr::CreateImplicit(
18767 Context, AliasName->
getName(),
true, Info);
18773 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18777 Diag(PrevDecl->
getLocation(), diag::warn_redefine_extname_not_applied)
18778 << (isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18781 (
void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name,
Attr));
18787 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18792 (void)WeakUndeclaredIdentifiers[Name].insert(
WeakInfo(
nullptr, NameLoc));
18801 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18802 LookupOrdinaryName);
18805 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18806 if (!PrevDecl->
hasAttr<AliasAttr>())
18807 if (
NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18808 DeclApplyPragmaWeak(TUScope, ND, W);
18810 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18815 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18820 if (FD->
hasAttr<SYCLSimdAttr>())
18822 if (FD->
hasAttr<SYCLDeviceAttr>() || FD->
hasAttr<SYCLKernelAttr>())
18825 if (getLangOpts().
CUDA)
18828 if (getLangOpts().OpenMP)
18829 return getLangOpts().OpenMPIsDevice
18837 assert(FD &&
"Expected non-null FunctionDecl");
18841 return FunctionEmissionStatus::TemplateDiscarded;
18843 if (LangOpts.SYCLIsDevice &&
18844 (FD->
hasAttr<SYCLDeviceAttr>() || FD->
hasAttr<SYCLKernelAttr>()))
18845 return FunctionEmissionStatus::Emitted;
18848 auto IsEmittedForExternalSymbol = [
this, FD]() {
18855 getASTContext().GetGVALinkageForFunction(Def));
18858 if (LangOpts.OpenMPIsDevice) {
18867 if (DevTy.hasValue())
18868 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18869 return FunctionEmissionStatus::OMPDiscarded;
18872 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18873 if (IsEmittedForExternalSymbol())
18874 return FunctionEmissionStatus::Emitted;
18878 return FunctionEmissionStatus::OMPDiscarded;
18879 }
else if (LangOpts.OpenMP > 45) {
18885 if (DevTy.hasValue())
18886 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18887 return FunctionEmissionStatus::OMPDiscarded;
18890 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18891 return FunctionEmissionStatus::Emitted;
18893 if (LangOpts.CUDA) {
18900 return FunctionEmissionStatus::CUDADiscarded;
18901 if (!LangOpts.CUDAIsDevice &&
18903 return FunctionEmissionStatus::CUDADiscarded;
18905 if (IsEmittedForExternalSymbol())
18906 return FunctionEmissionStatus::Emitted;
18909 if (getLangOpts().SYCLIsDevice) {
18910 if (!FD->
hasAttr<SYCLDeviceAttr>() && !FD->
hasAttr<SYCLKernelAttr>())
18923 return FunctionEmissionStatus::Emitted;
18939 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18940 IdentifyCUDATarget(Callee) == CFT_Global;